<?php
/**
 * 工程款支付报审表
 **/
namespace Admin\Controller;
use Common\Controller\AuditparentController;

class PaymentReviewController extends AuditparentController{
	protected $TMList_model,$QPSummary_model,$OMList_model,$PProgress_model,$PSummary_model,$PC_model;
	public function _initialize() {
		parent::_initialize();
		$this->deal_model = D("Common/PaymentReview");
		$this->TMList_model= D("Common/TechnicalMeasuresList");
		$this->QPSummary_model =  D("Common/QuotedPriceSummary");
		$this->OMList_model =  D("Common/OrgMeasuresList");
		$this->PProgress_model = D("Common/ProjectProgress");
		$this->PSummary_model = D("Common/ProjectSummary");
		$this->PC_model = D("Common/PaymentCertificate");
		
		$this->check = array('code', 'report_type');
		
		// 当前审批流程
		$this->function = "payment";
		$this->subfunction = "1";
	}
	
	// 首页查看
	public function index(){
		/**搜索条件**/
		// $where = "d.is_deleted <> 1 AND d.report_type = 1 AND (d.is_publish=1 OR d.add_user=".session('ADMIN_ID').") AND (deps.department_role = '".session('Role')."' OR '".session('Role')."' in (0,1,2,3))";

		// 当前登录人 20171228
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId);
		$where = "d.is_deleted <> 1 AND d.report_type = 1 ";
		$where = $where." AND (
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('1','2','3'))))
            OR
            (d.is_publish = 1   
                AND (
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u1 LEFT JOIN hzzy_department d1 ON u1.department_id = d1.id WHERE u1.id=$adminId)
                        <= 
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u2 LEFT JOIN hzzy_department d2 ON u2.department_id = d2.id WHERE u2.id=d.add_user)
                )
                AND  '$adminGroup[department_role]' in ('1','2','3')
                OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department)
            )
            OR
            ((SELECT role_id FROM hzzy_users WHERE id=$adminId) = 0 AND d.is_publish = 1)
        )";

		$isAudit = ",(
		CASE
			WHEN audit_status != 1 THEN 2
			WHEN audit_level = 2 AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3' AND d.add_department = ".session('deptid')." THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 1 
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '2'
					AND (
						SELECT 2 * fd.`level` + 1
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid')." ) = d.audit_level
			THEN 1
			WHEN audit_level > 2 AND audit_status = 1 AND audit_level % 2 = 0
					AND (SELECT role_id FROM ".C('DB_PREFIX')."users WHERE id = '".session('ADMIN_ID')."') = '3'
					AND (
						SELECT 2 * fd.`level` + 2
						FROM ".C('DB_PREFIX')."audit_flow_dept fd
						LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '".$this->function."' AND f.subfunction = '".$this->subfunction."' AND fd.department_id = ".session('deptid').") = d.audit_level
			THEN 1
			ELSE 2
		END
		) as isaudit";
		
		/*$where = $where." AND (
			d.add_user = '".session('ADMIN_ID')."'
			OR 1 = '".session('ADMIN_ID')."'
			OR 
			(d.add_department = '".session('deptid')."' AND '".session('Role')."' = 3)
			OR
			('".session('deptid')."' IN (SELECT department_id FROM ".C('DB_PREFIX')."audit_flow af1 LEFT JOIN ".C('DB_PREFIX')."audit_flow_dept afd ON af1.id = afd.flow_id WHERE af1.FUNCTION = '".$this->function."' AND af1.subfunction = '".$this->subfunction."'))
			OR (
				d.audit_status = 3 AND (
					(SELECT department_role FROM ".C('DB_PREFIX')."department WHERE id='".session('deptid')."') <= (SELECT department_role
					FROM ".C('DB_PREFIX')."audit_flow_dept fd 
					LEFT JOIN ".C('DB_PREFIX')."audit_flow f ON fd.flow_id = f.id 
					LEFT JOIN ".C('DB_PREFIX')."department dp ON dp.id = fd.department_id 
					WHERE f.function='".$this->function."' AND f.subfunction='".$this->subfunction."'
					ORDER BY fd.`LEVEL` DESC
					LIMIT 1)
				) OR (
					'".session('ADMIN_ID')."' IN (SELECT add_user FROM ".C('DB_PREFIX')."audit_history WHERE function='".$this->function."' AND subfunction='".$this->subfunction."' AND table_id = d.id)
				) OR (d.add_department = ".session('deptid').")
			)
		)";*/
		
		

		$count = $this->deal_model->alias("d")
			->field('d.*,deps.department_role role')
			->join(array(
				' LEFT JOIN (SELECT dm.id,dm.department_role,uss.id uid from '.C('DB_PREFIX').'department as dm left join '.C('DB_PREFIX').'users as uss on uss.department_id = dm.id ) deps ON deps.uid = d.add_user ',
            ))
		    ->where($where)
		    ->count();
        $page = $this->page($count, 20);
		
		$results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name,f.level,h.time,de.department_name,dep.department_name department_name_first,deps.department_role role,u1.real_name as usname,DATE_ADD(h.time, INTERVAL 7 DAY) as newtime,
						(CASE 
							WHEN audit_level > 2 THEN ad.department_name
							ELSE ad1.department_name
						END) as curdept'.$isAudit)
            ->join(array(
                ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow f ON f.function = \''.$this->function."' AND f.subfunction='".$this->subfunction."'",
				' LEFT JOIN (SELECT table_id,MAX(add_time) as time,add_user,add_department FROM (SELECT * FROM '.C('DB_PREFIX').'audit_history WHERE `function` = \''.$this->function.'\' AND subfunction = \''.$this->subfunction.'\' ORDER BY id DESC) as T GROUP BY table_id) as h ON h.table_id = d.id',
				' LEFT JOIN '.C('DB_PREFIX').'department de ON h.add_department = de.id',
				' LEFT JOIN '.C('DB_PREFIX').'users u1 ON h.add_user = u1.id ',
				' LEFT JOIN '.C('DB_PREFIX').'department dep ON dep.id = d.add_department_first ',
				' LEFT JOIN (SELECT dm.id,dm.department_role,uss.id uid from '.C('DB_PREFIX').'department as dm left join '.C('DB_PREFIX').'users as uss on uss.department_id = dm.id ) deps ON deps.uid = d.add_user ',
				
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow af ON af.`function` = \''.$this->function.'\' AND af.subfunction = \''.$this->subfunction.'\' ',
				' LEFT JOIN '.C('DB_PREFIX').'audit_flow_dept afd ON af.id = afd.flow_id AND afd.`level` = floor((audit_level - 1)/2) ',
				' LEFT JOIN '.C('DB_PREFIX').'department ad ON afd.department_id = ad.id ',
				' LEFT JOIN '.C('DB_PREFIX').'department ad1 ON d.add_department = ad1.id '
				
            ))
            ->where($where)
            ->order("d.add_time DESC")
            ->limit($page->firstRow, $page->listRows)
            ->select();
		//exit($this->deal_model->getLastSql());
        $this->assign("page", $page->show('Admin'));
        $this->assign("results",$results);
        $role_id = D("Common/Users")->where('id='.session('ADMIN_ID'))->getField('role_id');
        $this->assign("role_id",$role_id);
        //dump($results);
        $this->display();
		
		//$this->indexAuditPage($where);
	}

	// 工程清单量报表查看
	public function projectview(){
		$excel = array(
			'1' => '技术措施项目清单及计价表__建筑工程',
			'2' => '技术措施项目清单及计价表__安装工程',
			'3' => '单位工程报价汇总表',
			'4' => '工程项目报价汇总表',
			'5' => '组织措施项目（整体）清单及计价表',
			'6' => '工程形象进度完成情况'
		);
		$this->assign("excel", $excel);
		$this->display();
	}
	
	// 现场工程量计量表查看
	public function siteview(){
		$excel = array(
			'7' => '分部分项工程量清单及计价表_建筑工程',
			'8' => '分部分项工程量清单及计价表_安装工程'
		);
		$this->assign("excel", $excel);
		$this->display();
	}
	
	// 查看技术措施以及分部工程清单
	public function technicalview(){
		$where = array(
			'payment_review_id'	=> I('get.id',0,'intval')
		);

		$payment = $this->deal_model->field("is_publish")->where("id = ".I("get.id", '0', 'intval'))->find();

		$type = I('get.type',0,'intval');
		if($type == 1){
			$where['item_category'] = '1';
			$where['construction_category'] = '建筑工程';
		} elseif($type == 2){
			$where['item_category'] = '1';
			$where['construction_category'] = '安装工程';
		} elseif($type == 7){
			$where['item_category'] = '2';
			$where['construction_category'] = '建筑工程';
		} else {
			$where['item_category'] = '2';
			$where['construction_category'] = '安装工程';
		}

		if($payment["is_publish"]==1){
			$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' AND t.is_publish = 1) OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1)";
		}
		else{
			$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))";
		}

		//$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))";
		// 查询数据
		$options = $this->TMList_model->alias("t")
						->field("DISTINCT position_name")
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON t.payment_review_id = p.id',
						))
						->where($where)->select();


		$this->assign("options", $options);
		$sheet = I("get.sheet", 0, 'intval');
		$where['position_name'] = $options[$sheet]['position_name'];
		unset($where['_string']);
		$this->assign("sheet", $where['position_name']);
		$results = $this->TMList_model->where($where)->select();
		$this->assign("results", $results);
		$this->assign("type", $where['item_category']);
		// 跳转页面
		$this->display();
	}

	// 编辑单条数据,串联所有计算
	public function technical_post(){
		$type = I("post.type", '1');
		$saveData = array('id'	=> I("post.id", '0', 'intval'));
		// 施工方经办人操作
		if($type == 1){
			$saveData['complete_workload'] = I("post.value");
			$saveData['complete_total_value'] = I("post.total");
		// 监理方经办人操作
		} elseif($type == 2) {
			$saveData['approved_workload'] = I("post.value");
			$saveData['approved_workload_total_value'] = I("post.total");
		} elseif($type == 3){
			$saveData['complete_total_value'] = I("post.total");
		} else {
			$saveData['approved_workload_total_value'] = I("post.total");
		}
		// 保存数据
		$this->TMList_model->save($saveData);
		//如果是汇总数据，更新其他计算
		if($type==3||$type==4){
            $this->qpsEdit1($type);
        }
		$this->success("修改成功");
	}

	// 编辑单位工程报价汇总表 - 技术措施项目清单
	public function qpsEdit1($type){
		// 查询基础信息
		$base = $this->TMList_model->field("payment_review_id,item_category,position_name")->where("id = ".I("post.id", '0', 'intval'))->find();

		//合计技术措施项目清单/分部分项项目清单计价到单位工程报价汇总表
        $whereTechSum = array(
            'payment_review_id' => $base['payment_review_id'],
            'position_name'		=>  $base['position_name'],
            'order_id'			=> 3
        );
		// 查询建筑工程汇总
		$sql = "SELECT ".($type == 3 ? "complete_total_value as total " : "approved_workload_total_value as total ")."
				FROM ".C('DB_PREFIX')."technical_measures_list 
				WHERE payment_review_id = ".$base['payment_review_id']." AND item_category = ".$base['item_category']." 
					AND construction_category = '建筑工程' 
					AND position_name='".$base['position_name']."' AND item_code='合计'";
		$build = $this->TMList_model->query($sql);
		// 查询安装工程
		$sql = "SELECT ".($type == 3 ? "complete_total_value as total " : "approved_workload_total_value as total ")."
				FROM ".C('DB_PREFIX')."technical_measures_list 
				WHERE payment_review_id = ".$base['payment_review_id']." AND item_category = ".$base['item_category']." 
					AND construction_category = '安装工程' 
					AND position_name='".$base['position_name']."' AND item_code='合计'";
		$install = $this->TMList_model->query($sql);
		// 合计工作量
		$total = $build[0]['total'] + $install[0]['total'];
		if($base['item_category'] == 1){
			// 拼接修改语句
			$where = " AND payment_review_id = ".$base['payment_review_id']." AND position_name='".$base['position_name']."'";
			$sql = "UPDATE ".C('DB_PREFIX')."quoted_price_summary SET ".($type == 3 ? "report_total_amount" : "approved_total_amount")." = '".$total."'
					,".($type == 3 ? "report_construction_amount" : "approved_construction_amount")."='".$build[0]['total']."'
					,".($type == 3 ? "report_installation_amount" : "approved_installation_amount")."='".$install[0]['total']."' 
					,"."cumulative_completion_percent=(".$total."+last_approved_accumulated_amount)/list_total_amount*100"."
					WHERE order_id = '2'".$where;

			$this->QPSummary_model->execute($sql);

			// 查询组织措施项目清单
			$field = $type == 3 ? "report_construction_amount as build,report_installation_amount as install,report_total_amount as total" 
								: "approved_construction_amount as build,approved_installation_amount as install,approved_total_amount as total";
			$group = $this->QPSummary_model->field($field)->where("order_id = '1'" . $where)->find();
			
			// 计算
			$build = $build[0]['total'] + $group['build'];
			$install = $install[0]['total'] + $group['install'];
			$total = $total + $group['total'];
			
			// 拼接修改语句
			$sql = "UPDATE ".C('DB_PREFIX')."quoted_price_summary SET ".($type == 3 ? "report_total_amount" : "approved_total_amount")." = '".$total."'
					,".($type == 3 ? "report_construction_amount" : "approved_construction_amount")."='".$build."'
					,".($type == 3 ? "report_installation_amount" : "approved_installation_amount")."='".$install."' 
					WHERE order_id = '二'".$where;
			$this->QPSummary_model->execute($sql);
		} else {
			// 拼接修改语句
			$where = " AND payment_review_id = ".$base['payment_review_id']." AND position_name='".$base['position_name']."'";
			$sql = "UPDATE ".C('DB_PREFIX')."quoted_price_summary SET ".($type == 3 ? "report_total_amount" : "approved_total_amount")." = '".$total."'
					,".($type == 3 ? "report_construction_amount" : "approved_construction_amount")."='".$build[0]['total']."'
					,".($type == 3 ? "report_installation_amount" : "approved_installation_amount")."='".$install[0]['total']."' 
					,"."cumulative_completion_percent=(".$total."+last_approved_accumulated_amount)/list_total_amount"."
					WHERE order_id = '一'".$where;
			$this->QPSummary_model->execute($sql);
		}
		
		// 修改单位工程报价汇总 - 总报价
        /*
         * 需要计算汇总：
         * 3	排污费、社保费、公积金
         * 5	民工工伤保险费[（一+二+三+3+4）*费率]
         * 四	规费[3+4+5]
         * 五	税金[（一+二+三+四）*费率]
         * 六	总报价（一+二+三+四+五）
         */
        $whereUnitProject=array(
            'payment_review_id' => $base['payment_review_id'],
            'position_name'		=> $base['position_name']
            #'_string'				=> "order_id ='一'"
        );
        $fields=" order_id,item_name,
        list_total_amount,
        cumulative_completion_percent,
        last_report_accumulated_amount,
        last_approved_accumulated_amount,
        report_construction_amount,
        report_installation_amount,
        report_total_amount,
        approved_construction_amount,
        approved_installation_amount,
        approved_total_amount,
        is_publish";
        $unitProjectSummary=$this->QPSummary_model->field($fields)->where($whereUnitProject)->select();

        //* 3	排污费、社保费、公积金
        //公式: 排污费、社保费、公积金[报价合计]*(分部分项工程量清单[建筑工程]/分部分项工程量清单[报价合计])
        //公式: 排污费、社保费、公积金[报价合计]*分部分项工程量清单[累计完成百分比]-排污费、社保费、公积金[至上期末监理审核完成]
        $item3['report_total_amount'] = $unitProjectSummary[6]["list_total_amount"]*($unitProjectSummary[0]["report_construction_amount"]/$unitProjectSummary[0]["list_total_amount"]);
        $item3['approved_total_amount']=$unitProjectSummary[6]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
            -$unitProjectSummary[6]["last_approved_accumulated_amount"];
        $whereT = array(
            'payment_review_id' => $base['payment_review_id'],
            'position_name'		=>  $base['position_name'],
            'order_id'			=> 3
        );
        $this->QPSummary_model->where($whereT)->save($item3);

        //* 5	民工工伤保险费[（一+二+三+3+4）*费率]
        //公式：民工工伤保险费[报价合计]*分部分项工程量清单[累计完成百分比]-民工工伤保险费[至上期末监理审核完成]
        $item5['report_total_amount'] = ($unitProjectSummary[0]["report_total_amount"]
                +$unitProjectSummary[1]["report_total_amount"]
                +$unitProjectSummary[4]["report_total_amount"]
                +$unitProjectSummary[6]["report_total_amount"]
                +$unitProjectSummary[7]["report_total_amount"])*0.114/100;
        $item5['approved_total_amount']=$unitProjectSummary[8]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
            -$unitProjectSummary[8]["last_approved_accumulated_amount"];
        $whereT["order_id"] =  5;
        $this->QPSummary_model->where($whereT)->save($item5);

        //* 四	规费[3+4+5]
        $itemSum4['report_total_amount'] = $item3['report_total_amount']
                +$item5['report_total_amount']
                +$unitProjectSummary[7]["report_total_amount"];
        $itemSum4['approved_total_amount'] = $item3['approved_total_amount']
            +$item5['approved_total_amount']
            +$unitProjectSummary[7]["approved_total_amount"];
        $whereT["order_id"] =  '四';
        $this->QPSummary_model->where($whereT)->save($itemSum4);

        //* 五	税金[（一+二+三+四）*费率]
        $itemSum5['report_total_amount'] = ($unitProjectSummary[0]["report_total_amount"]
                +$unitProjectSummary[1]["report_total_amount"]
                +$unitProjectSummary[4]["report_total_amount"]
                +$itemSum4['report_total_amount'])*3.577/100;
        $itemSum5['approved_total_amount']=$unitProjectSummary[9]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
            -$unitProjectSummary[9]["last_approved_accumulated_amount"];

        $whereT["order_id"] =  '五';
        $this->QPSummary_model->where($whereT)->save($itemSum5);

        //* 六	总报价（一+二+三+四+五）
        $itemSum6['report_total_amount'] = $unitProjectSummary[0]["report_total_amount"]
                +$unitProjectSummary[1]["report_total_amount"]
                +$unitProjectSummary[4]["report_total_amount"]
                +$itemSum4['report_total_amount']
                +$itemSum5['report_total_amount'];
        $itemSum6['approved_total_amount'] = $unitProjectSummary[0]["approved_total_amount"]
            +$unitProjectSummary[1]["approved_total_amount"]
            +$unitProjectSummary[4]["approved_total_amount"]
            +$itemSum4['approved_total_amount']
            +$itemSum5['approved_total_amount'];
        $whereT["order_id"] =  '六';
        $this->QPSummary_model->where($whereT)->save($itemSum6);

        //更新总报价大写
        $itemSumAll['item_name'] =$this->number2chinese($itemSum6['report_total_amount'], true, false);
        $whereT["order_id"] =  '总报价(大写)：';
        $this->QPSummary_model->where($whereT)->save($itemSumAll);

        //判断当前单位工程项目汇总是否发布，如果发布，则更新工程项目汇总表，否则不更新
        if($unitProjectSummary[10]["is_publish"]=="1"){
            $unitItemSummary["report_construction_amount"]=$itemSum6['report_total_amount'];
            $unitItemSummary["approved_total_amount"]=$itemSum6['approved_total_amount'];
            $unitItemSummary["report_amount_percent"]=$itemSum6['approved_total_amount']/$unitProjectSummary["list_total_amount"];
            $unitItemSummary["cumulative_completion_percent"]=($itemSum6['approved_total_amount']+$unitProjectSummary["last_approved_accumulated_amount"]) /
                $unitProjectSummary["list_total_amount"];

            //更新工程项目汇总中的单位工程汇总数据
            $this->PSummary_model->where(
                array(
                    'payment_review_id' => $base['payment_review_id'],
                    'item_name'			=> $base['position_name']
                )
            )->save($unitItemSummary);

            //计算工程项目报价汇总中，单位工程费合计一列的值
            $sumItemsWhere=array(
                'payment_review_id' => $base['payment_review_id'],
                '_string'=>"item_name in ('1#病房楼','2#病房楼','3#病房楼','门诊医技楼','后勤值班楼','行政科研楼','高压氧舱楼','后勤服务楼','发热门诊楼','垃圾房','地下室','基坑围护')"
            );
            $sumfields="SUM(list_total_amount) AS list_total_amount,
                    SUM(last_approved_accumulated_amount) AS last_approved_accumulated_amount,
                    SUM(report_construction_amount) AS report_construction_amount,
                    SUM(approved_total_amount) AS approved_total_amount";

            $sumItems = $this->PSummary_model->field($sumfields)->where($sumItemsWhere)->find();

            $itemSummary["report_construction_amount"]=$sumItems['report_construction_amount'];
            $itemSummary["approved_total_amount"]=$sumItems['approved_total_amount'];
            $itemSummary["report_amount_percent"]=$sumItems['approved_total_amount']/$sumItems["list_total_amount"];
            $itemSummary["cumulative_completion_percent"]=($sumItems['approved_total_amount']+$sumItems["last_approved_accumulated_amount"]) / $sumItems["list_total_amount"];
            $this->PSummary_model->where(
                array(
                    'payment_review_id' => $base['payment_review_id'],
                    'item_name'			=> '单位工程费合计'
                )
            )->save($itemSummary);

            //汇总工程项目汇总合计值，二以下需要计算的所有
            /**
             * 需要汇总
             * 1.一、至本期累计完成百分比
             * 2.一、监理审核（元）
             * 3.农民工工伤保险费{[（一）+（二）+3+4]*费率}
             * 4.税金{[（一）+（二）+（三）]*费率}
             */
            $wherePorject=array(
                'payment_review_id' => $base['payment_review_id'],
            );
            $fields="id,payment_review_id,
                order_id,item_name,
                list_total_amount,
                last_approved_accumulated_amount,
                cumulative_completion_percent,
                report_amount_percent,
                report_construction_amount,
                approved_total_amount";

            //取出工程项目汇总所有数据
            $projectSummary=$this->PSummary_model->field($fields)->where($wherePorject)->select();

            $approvedUsePercent=($projectSummary[0]["approved_total_amount"]+$projectSummary[0]["last_approved_accumulated_amount"])/$projectSummary[0]["list_total_amount"];

            //1	组织措施项目清单
            $wherea = array(
                'payment_review_id' => $base['payment_review_id'],
                'order_id' => '合计'
            );
            $orgml = $this->OMList_model->where($wherea)->find();
            $item211["id"]= $projectSummary[15]["id"];
            $item211["report_construction_amount"]=$orgml['report_amount'];
            $item211["approved_total_amount"]=$orgml['approved_amount'];
            $item211["report_amount_percent"]=$item211['report_construction_amount']/$projectSummary[15]["list_total_amount"];
            $item211["cumulative_completion_percent"]=($item211['approved_total_amount']+$projectSummary[15]["last_approved_accumulated_amount"]) / $projectSummary[15]["list_total_amount"];
            $this->PSummary_model->save($item211);

            //（一）	整体措施项目清单（1+2）
            $item211["id"]=$projectSummary[14]["id"];
            $this->PSummary_model->save($item211);



            //5	农民工工伤保险费{[（一）+（二）+3+4]*费率}
            $item235["id"]= $projectSummary[21]["id"];
            $item235["report_construction_amount"]=($item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$projectSummary[19]["report_construction_amount"]
                    +$projectSummary[20]["report_construction_amount"])*0.114/100;
            $item235["approved_total_amount"]=$projectSummary[21]["list_total_amount"]*$approvedUsePercent-$projectSummary[21]["last_approved_accumulated_amount"];
            $item235["report_amount_percent"]=$item235['approved_total_amount']/$projectSummary[21]["list_total_amount"];
            $item235["cumulative_completion_percent"]=($item235['approved_total_amount']+$projectSummary[21]["last_approved_accumulated_amount"]) / $projectSummary[21]["list_total_amount"];
            $this->PSummary_model->save($item235);

            #(三)整体措施项目规费[3+4+5]
            $itemD345["id"]= $projectSummary[18]["id"];
            //本期完成
            $itemD345["report_construction_amount"]=$projectSummary[19]["report_construction_amount"]
                +$projectSummary[20]["report_construction_amount"]
                +$item235["report_construction_amount"];
            //监理审核
            $itemD345["approved_total_amount"]=$projectSummary[19]["approved_total_amount"]
                +$projectSummary[20]["approved_total_amount"]
                +$item235["approved_total_amount"];
            $itemD345["report_amount_percent"]=$itemD345["approved_total_amount"]/$projectSummary[18]["list_total_amount"];
            $itemD345["cumulative_completion_percent"]=($itemD345["approved_total_amount"]+$projectSummary[18]["last_approved_accumulated_amount"]) / $projectSummary[18]["list_total_amount"];
            $this->PSummary_model->save($itemD345);

            //（四）税金{[（一）+（二）+（三）]*费率}
            $itemD4["id"]= $projectSummary[22]["id"];
            //本期完成
            $itemD4["report_construction_amount"]=($item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$itemD345["report_construction_amount"])*3.577/100;
            //监理审核
            $itemD4["approved_total_amount"]=$projectSummary[22]["list_total_amount"]*$approvedUsePercent
                -$projectSummary[22]["last_approved_accumulated_amount"];
            $itemD4["report_amount_percent"]=$itemD4['approved_total_amount']/$projectSummary[22]["list_total_amount"];
            $itemD4["cumulative_completion_percent"]=($itemD4['approved_total_amount']+$projectSummary[22]["last_approved_accumulated_amount"]) / $projectSummary[22]["list_total_amount"];
            $this->PSummary_model->save($itemD4);
            //二、未纳入单位工程费的其他费用[（一）+（二）+（三）+（四）]
            $itemD2["id"]= $projectSummary[13]["id"];
            //本期完成
            $itemD2["report_construction_amount"]=$item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$itemD345["report_construction_amount"]
                    +$itemD4["report_construction_amount"];
            //监理审核
            $itemD2["approved_total_amount"]=$item211["approved_total_amount"]
                +$projectSummary[17]["approved_total_amount"]
                +$itemD345["approved_total_amount"]
                +$itemD4["approved_total_amount"];
            $itemD2["report_amount_percent"]=$itemD2['approved_total_amount']/$projectSummary[13]["list_total_amount"];
            $itemD2["cumulative_completion_percent"]=($itemD2['approved_total_amount']+$projectSummary[13]["last_approved_accumulated_amount"]) / $projectSummary[13]["list_total_amount"];
            $this->PSummary_model->save($itemD2);

            //总报价[一+二]
            $itemZ["id"]= $projectSummary[23]["id"];
            //本期完成
            $itemZ["report_construction_amount"]=$projectSummary[0]["report_construction_amount"]
                +$itemD2["report_construction_amount"];
            //监理审核
            $itemZ["approved_total_amount"]=$projectSummary[0]["approved_total_amount"]
                +$itemD2["approved_total_amount"];
            $itemZ["report_amount_percent"]=$itemZ['approved_total_amount']/$projectSummary[23]["list_total_amount"];
            $itemZ["cumulative_completion_percent"]=($itemZ['approved_total_amount']+$projectSummary[23]["last_approved_accumulated_amount"]) / $projectSummary[23]["list_total_amount"];
            $this->PSummary_model->save($itemZ);
            //更新总报价(大写)：
            $itemZD["id"]= $projectSummary[24]["id"];
            $itemZD["item_name"]=$this->number2chinese($itemZ['report_construction_amount'], true, false);
            $this->PSummary_model->save($itemZD);

            //更新 工程款支付报审表 hzzy_PaymentReview
            $PaymentReview_new['id'] = $base['payment_review_id'];
            $PaymentReview_new['list_pricing'] = $itemZ["report_construction_amount"];
            $PaymentReview_new['payables'] = $itemZ["report_construction_amount"]*0.75;
            $PaymentReview_new['supervision_amount'] = $itemZ["approved_total_amount"]*0.75;
            $PaymentReview_new['supervision_amount_words'] = $this->number2chinese(round($PaymentReview_new['supervision_amount'],2),
                true, false);
            $PaymentReview_new['agent_construction_amount'] = $PaymentReview_new['supervision_amount'];
            $PaymentReview_new['agent_construction_amount_words'] = $PaymentReview_new['supervision_amount_words'];
            $PaymentReview_new['construction_amount'] = $PaymentReview_new['supervision_amount'];
            $PaymentReview_new['construction_amount_words'] = $PaymentReview_new['supervision_amount_words'];
            $this->deal_model->save($PaymentReview_new);
        }



		// 工程项目报价汇总表
		/*$val = ($type == 3 ? "report_construction_amount" : "approved_total_amount");
		$this->PSummary_model
			->where(
				array(
					'payment_review_id' => $base['payment_review_id'], 
					'item_name'			=> $base['item_category']
				)
			)
			->save(array($val => $total['total']));
		// 工程项目报价汇总表 - 合计
		$type = "'1#病房楼','2#病房楼','3#病房楼','门诊医技楼','后勤值班楼','行政科研楼','高压氧舱楼','后勤服务楼','发热门诊楼','垃圾房','地下室','基坑围护'";
		$total = $this->PSummary_model->field("SUM(".$val.") as total ")->where("'payment_review_id' = ".$base['payment_review_id']." AND item_name IN(".$type.")")->find();
		$this->PSummary_model
			->where(
				array(
					'payment_review_id' => $base['payment_review_id'], 
					'item_name'			=> '单位工程费合计'
				)
			)
			->save(array($val => $total['total']));
		*/
		
	}
	
	// 查看单位工程报价汇总表
	public function qpsview(){
		$where = array(
			'payment_review_id'	=> I('get.id',0,'intval')
		);
		//$payment = $this->deal_model->field("is_publish")->where($where)->find();
		$payment = $this->deal_model->field("is_publish")->where("id = ".I("get.id", '0', 'intval'))->find();
		

		if($payment["is_publish"]==1){
			$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' AND t.is_publish = 1) OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1)";
		}
		else{
			$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))";
		}

		//$where['_string'] = "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))";
		// 查询数据
		$options = $this->QPSummary_model->alias("t")
						->field("DISTINCT position_name")
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON t.payment_review_id = p.id',
						))
						->where($where)->select();
		$this->assign("options", $options);
		
		$sheet = I("get.sheet", 0, 'intval');
		$where['position_name'] = $options[$sheet]['position_name'];
		unset($where['_string']);
		$this->assign("sheet", $where['position_name']);
		$results = $this->QPSummary_model->where($where)->select();
		$this->assign("results", $results);
		
		// 跳转页面
		$this->display();
	}
	
	// 查看工程项目报价汇总表
	public function psview(){
		$where = array(
			'payment_review_id'	=> I('get.id',0,'intval'),
			'_string'			=> "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))"
		);
		$results = $this->PSummary_model->alias("t")
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON t.payment_review_id = p.id',
						))
						->where($where)
						->select();
		$this->assign("results", $results);
		
		// 跳转页面
		$this->display();
	}
	
	// 组织措施项目（整体）清单及计价表
	public function omlview(){
		$where = array(
			'payment_review_id'	=> I('get.id',0,'intval'),
			'_string'			=> "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))"
		);
		$results = $this->OMList_model->alias("t")
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON t.payment_review_id = p.id',
						))
						->where($where)->select();
		$this->assign("results", $results);
		
		// 跳转页面
		$this->display();
	}
	// 修改单条数据
	public function oml_post(){
		$saveData = array(
			'id'	=> I("post.id")
		);
		$type = I("post.type");
		$type == 1 ?  $saveData['report_amount'] = I("post.value") : $saveData['approved_amount'] = I("post.value");
		$this->OMList_model->save($saveData);
		$this->success("修改成功");
	}
	// 修改单位工程报价汇总表 - 组织措施项目(整体)清单及计价表
	public function qpsEdit2($type){
		// 计算总金额
		$val = ($type == 1 ? "report_amount" : "approved_amount");
		$total = $this->OMList_model->field("SUM(".$val.") as total")
					->where("order_id <> '合计' AND payment_review_id = " . I("post.id"))
					->find();
		$this->OMList_model->where()->save(array($val => $total));
		// 修改项目工程报价汇总 - 组织措施项目清单
		
		// 查询基础信息
		$base = $this->TMList_model->field("payment_review_id,item_category,position_name")->where("id = ".I("post.id", '0', 'intval'))->find();
		
		// 拼接修改语句
		$where = " AND payment_review_id = ".$base['payment_review_id'];
		$sql = "UPDATE ".C('DB_PREFIX')."project_summary SET ".($type == 3 ? "report_construction_amount" : "approved_total_amount")." = '".$total."' 
				WHERE (item_name = '组织措施项目清单' OR item_name ='整体措施项目清单（1+2）') AND payment_review_id = ".$base['payment_review_id'];
		$this->QPSummary_model->execute($sql);
	}
		
	// 工程形象进度完成情况
	public function ppview(){
		$where = array(
			'payment_review_id'	=> I('get.id',0,'intval'),
			'_string'			=> "(p.add_user = '".session('ADMIN_ID')."' OR (p.add_user != '".session('ADMIN_ID')."' AND t.is_publish = 1))"
		);
		$results = $this->PProgress_model->alias("t")
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON t.payment_review_id = p.id',
						))
						->where($where)->select();
		$this->assign("results", $results);
		
		// 跳转页面
		$this->display();
	}
	// 保存形象进度
	public function pp_post(){
		$saveData = array(
			'id'	=> I("post.id"),
			'approved_workload' => I("post.value")
		);
		$this->PProgress_model->save($saveData);
		$this->success("修改成功");
	}
	
	// 数据新增
	public function addPostImp(){
		if(IS_POST){
			$this->dataCheck();
            $id = I("post.id", 0, 'intval');
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create()!==false) {
				$result = $this->deal_model->add($data);
				if ($result!==false) {
					// 创建审批 一级流程数据
					$history = array(
						'table_id'			=> $result,
						'audit_status'		=> 1,
						'audit_reason'		=> '新建表单',
						'amount_in_words'	=> '',
						'audit_level'		=> 1
					);
					$data = array_merge($history, $this->auditAdd());
					$this->auditHistoryModel->add($data);
					$uploadType = I("post.uploadType", '');
					if($uploadType == ''){
						$this->Summary($result);
						//exit("保存成功！");
						$this->success("保存成功！", U("PaymentReview/view", array("id" => $result)));
					} elseif($uploadType == '1'){
						$this->redirect('PaymentReview/projectview', array("id" => $result, 'isAudit' => 1, 'level' => 2, 'deptId' => session('deptid'), 'isUpload' => 1), 0, '页面跳转中...');
					} else {
						$this->redirect('PaymentReview/siteview', array("id" => $result, 'isAudit' => 1, 'level' => 2, 'deptId' => session('deptid'), 'isUpload' => 1), 0, '页面跳转中...');
					}
				} else {
					$this->error("添加失败！");
				}
            } else {
                $this->error($this->deal_model->getError());
            }
        }
	}
	
	// 修改
	public function edit(){
		$this->editdisplay();
	}
	public function edit_post(){
		if (IS_POST) {
			$this->dataCheck();
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create()!==false) {
                $result=$this->deal_model->save($data);
                if ($result !== false) {
					$uploadType = I("post.uploadType", '');
					if($uploadType == ''){
						$this->Summary(I("post.id", 0, 'intval'));
						//exit("保存成功！");
						$this->success("保存成功！", U("PaymentReview/view", array("id" => $data['id'])));
					} elseif($uploadType == '1'){
						$this->redirect('PaymentReview/projectview', array("id" => $data['id'], 'isAudit' => 1, 'level' => 2, 'deptId' => session('deptid'), 'isUpload' => 1), 0, '页面跳转中...');
					} else {
						$this->redirect('PaymentReview/siteview', array("id" => $data['id'], 'isAudit' => 1, 'level' => 2, 'deptId' => session('deptid'), 'isUpload' => 1), 0, '页面跳转中...');
					}
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
	}
	
	// 修改数据汇总信息
	public function Summary($tableId){
		$sheetType = array(
			'1#病房楼',
			'2#病房楼',
			'3#病房楼',
			'门诊医技楼',
			'后勤值班楼',
			'行政科研楼',
			'高压氧舱楼',
			'后勤服务楼',
			'发热门诊楼',
			'垃圾房',
			'地下室',
			'基坑围护'
		);
		
		$field = "SUM(complete_total_value) as complete,SUM(approved_workload_total_value) as approved";
		$field1 = "SUM(report_total_amount) as report,SUM(approved_total_amount) as approved";
		foreach($sheetType as $key => $v){
			/*
			 * 查询本期分部分项合计值
			 */
			// 查询建筑工程
			$where = array(
				'item_category'			=> 2,
				'construction_category'	=> '建筑工程',
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'is_publish'			=> '1',
				'item_code'				=> '合计'
			);
			$data1 = $this->TMList_model->field($field)->where($where)->find();
			// 查询安装工程
			$where['construction_category'] = '安装工程';
			$data2 = $this->TMList_model->field($field)->where($where)->find();
			// 修改单位工程报价汇总表 - 分部分项工程量清单
			$saveData = array(
				'report_construction_amount'	=> $data1['complete'] != NULL ? $data1['complete'] : 0,
				'report_installation_amount'	=> $data2['complete'] != NULL ? $data2['complete'] : 0,
				'report_total_amount'			=> ($data1['complete'] != NULL ? $data1['complete'] : 0) + ($data2['complete'] != NULL ? $data2['complete'] : 0),
				'approved_construction_amount'	=> $data1['approved'] != NULL ? $data1['approved'] : 0,
				'approved_installation_amount'	=> $data2['approved'] != NULL ? $data2['approved'] : 0,
				'approved_total_amount'			=> ($data1['approved'] != NULL ? $data1['approved'] : 0) + ($data2['approved'] != NULL ? $data2['approved'] : 0)
			);
			unset($data1);
			unset($data2);
			$saveWhere = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'order_id'				=> '一',
				'item_name'				=> '分部分项工程量清单'
			);
			$this->QPSummary_model->where($saveWhere)->save($saveData);
			unset($saveWhere);
			/**
			 * 技术措施项目清单
			 **/

			// 查询建筑工程
			$where = array(
				'item_category'			=> 1,
				'construction_category'	=> '建筑工程',
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'is_publish'			=> '1',
				'item_code'				=> '合计'
			);
			$data1 = $this->TMList_model->field($field)->where($where)->find();
			// 查询安装工程
			$where['construction_category'] = '安装工程';
			$data2 = $this->TMList_model->field($field)->where($where)->find();
			// 修改单位工程报价汇总表 - 分部分项工程量清单
			$saveData = array(
				'report_construction_amount'	=> $data1['complete'] != NULL ? $data1['complete'] : 0,
				'report_installation_amount'	=> $data2['complete'] != NULL ? $data2['complete'] : 0,
				'report_total_amount'			=> ($data1['complete'] != NULL ? $data1['complete'] : 0) + ($data2['complete'] != NULL ? $data2['complete'] : 0),
				'approved_construction_amount'	=> $data1['approved'] != NULL ? $data1['approved'] : 0,
				'approved_installation_amount'	=> $data2['approved'] != NULL ? $data2['approved'] : 0,
				'approved_total_amount'			=> ($data1['approved'] != NULL ? $data1['approved'] : 0) + ($data2['approved'] != NULL ? $data2['approved'] : 0)
			);
			unset($data1);
			unset($data2);
			$saveWhere = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'_string'				=> "(order_id = '2' AND item_name = '技术措施项目清单') OR (order_id = '二' AND item_name = '措施项目清单（1+2）')"
			);
			$this->QPSummary_model->where($saveWhere)->save($saveData);
			unset($saveWhere);

			
	        /*
	         * 单位工程报价汇总表需要计算汇总：
	         * 3	排污费、社保费、公积金
	         * 5	民工工伤保险费[（一+二+三+3+4）*费率]
	         * 四	规费[3+4+5]
	         * 五	税金[（一+二+三+四）*费率]
	         * 六	总报价（一+二+三+四+五）
	         */
	        $whereUnitProject=array(
	            'payment_review_id' => $tableId,
	            'position_name'		=> $v,
	            //'_string'				=> "order_id ='一'"	            
	        );
	        $fields=" order_id,item_name,
	        list_total_amount,
	        cumulative_completion_percent,
	        last_report_accumulated_amount,
	        last_approved_accumulated_amount,
	        report_construction_amount,
	        report_installation_amount,
	        report_total_amount,
	        approved_construction_amount,
	        approved_installation_amount,
	        approved_total_amount,
	        is_publish";
	        $unitProjectSummary=$this->QPSummary_model->field($fields)->where($whereUnitProject)->select();

	        //* 3	排污费、社保费、公积金
	        //公式: 排污费、社保费、公积金[报价合计]*(分部分项工程量清单[建筑工程]/分部分项工程量清单[报价合计])
	        //公式: 排污费、社保费、公积金[报价合计]*分部分项工程量清单[累计完成百分比]-排污费、社保费、公积金[至上期末监理审核完成]
	        //本期完成合计
	        $item3['report_total_amount'] = $unitProjectSummary[6]["list_total_amount"]*($unitProjectSummary[0]["report_construction_amount"]/$unitProjectSummary[0]["list_total_amount"]);
	        //
	        $item3['approved_total_amount']=$unitProjectSummary[6]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
	            -$unitProjectSummary[6]["last_approved_accumulated_amount"];
	        $whereT = array(
	            'payment_review_id' => $table,
	            'position_name'		=>  $v,
	            'order_id'			=> 3
	        );
	        $this->QPSummary_model->where($whereT)->save($item3);

	        //* 5	民工工伤保险费[（一+二+三+3+4）*费率]
	        //公式：民工工伤保险费[报价合计]*分部分项工程量清单[累计完成百分比]-民工工伤保险费[至上期末监理审核完成]
	        $item5['report_total_amount'] = ($unitProjectSummary[0]["report_total_amount"]
	                +$unitProjectSummary[1]["report_total_amount"]
	                +$unitProjectSummary[4]["report_total_amount"]
	                +$unitProjectSummary[6]["report_total_amount"])*0.114/100;
	        $item5['approved_total_amount']=$unitProjectSummary[8]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
	            -$unitProjectSummary[8]["last_approved_accumulated_amount"];
	        $whereT["order_id"] =  5;
	        $this->QPSummary_model->where($whereT)->save($item5);

	        //* 四	规费[3+4+5]
	        $itemSum4['report_total_amount'] = $item3['report_total_amount']
	                +$item5['report_total_amount']
	                +$unitProjectSummary[7]["report_total_amount"];
	        $itemSum4['approved_total_amount'] = $item3['approved_total_amount']
	            +$item5['approved_total_amount']
	            +$unitProjectSummary[7]["approved_total_amount"];
	        $whereT["order_id"] =  '四';
	        $this->QPSummary_model->where($whereT)->save($itemSum4);

	        //* 五	税金[（一+二+三+四）*费率]
	        $itemSum5['report_total_amount'] = ($unitProjectSummary[0]["report_total_amount"]
	                +$unitProjectSummary[1]["report_total_amount"]
	                +$unitProjectSummary[4]["report_total_amount"]
	                +$itemSum4['report_total_amount'])*3.577/100;
	        $itemSum5['approved_total_amount']=$unitProjectSummary[9]["list_total_amount"]*$unitProjectSummary[0]["cumulative_completion_percent"]/100
	            -$unitProjectSummary[9]["last_approved_accumulated_amount"];

	        $whereT["order_id"] =  '五';
	        $this->QPSummary_model->where($whereT)->save($itemSum5);

	        //* 六	总报价（一+二+三+四+五）
	        $itemSum6['report_total_amount'] = $unitProjectSummary[0]["report_total_amount"]
	                +$unitProjectSummary[1]["report_total_amount"]
	                +$unitProjectSummary[4]["report_total_amount"]
	                +$itemSum4['report_total_amount']
	                +$itemSum5['report_total_amount'];
	        $itemSum6['approved_total_amount'] = $unitProjectSummary[0]["approved_total_amount"]
	            +$unitProjectSummary[1]["approved_total_amount"]
	            +$unitProjectSummary[4]["approved_total_amount"]
	            +$itemSum4['approved_total_amount']
	            +$itemSum5['approved_total_amount'];
	        $whereT["order_id"] =  '六';
	        $this->QPSummary_model->where($whereT)->save($itemSum6);

	        //更新总报价大写
	        $itemSumAll['item_name'] =$this->number2chinese($itemSum6['report_total_amount'], true, false);
	        $whereT["order_id"] =  '总报价(大写)：';
	        $this->QPSummary_model->where($whereT)->save($itemSumAll);


			/**
			 * 计算单位工程报价汇总
			 **/
			$where = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'_string'				=> "order_id IN('一','二','三','四','五')"
			);
			$total = $this->QPSummary_model->field($field1)->where($where)->find();
			$saveData1 = array(
				'report_total_amount' => !$total || $total['report'] == NULL ? 0 : $total['report'],
				'approved_total_amount' => !$total  || $total['approved'] == NULL? 0 : $total['approved']
				
			);
			unset($total);
			$saveWhere = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'order_id'				=> '六',
				'item_name'				=> '总报价（一+二+三+四+五）'
			);
			$this->QPSummary_model->where($saveWhere)->save($saveData1);
			unset($saveWhere);
			//echo "<hr />";
			/**
			 * 修改 总报价(大写)
			 **/
			$saveData2 = array(
				'item_name'	=> $this->number2chinese($saveData1['report_total_amount'], true, false)
			);
			$saveWhere = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'order_id'				=> array("like", '总报价%')
			);
			$this->QPSummary_model->where($saveWhere)->save($saveData2);
			unset($saveWhere);
			/**
			 * 修改 工程项目报价汇总
			 * 在数据库取出当前提交的单位工程项目报价汇总表 六的值
			 **/

			$where = array(
				'payment_review_id'		=> $tableId,
				'position_name'			=> $v,
				'order_id'				=> '六',
				'is_publish'			=> 1
			);
			$fields="last_approved_accumulated_amount as sum1,report_total_amount as sum2,approved_total_amount as sum3";
			$sum = $this->QPSummary_model->field($fields)->where($where)->find();


			$saveData3 = array(
				'last_approved_accumulated_amount'=>$sum['sum1']==NULL? 0: $sum['sum1'],
				'report_construction_amount'	=> $sum['sum2']==NULL? 0:$sum['sum2'],
				'approved_total_amount'			=> $sum['sum3']==NULL?0:$sum['sum3']
			);
			$saveWhere = array(
				'payment_review_id'		=> $tableId,
				'item_name'				=> $v
			);
			$this->PSummary_model->where($saveWhere)->save($saveData3);
			unset($saveWhere);
			unset($fields);
			unset($where);
		//}

            //汇总工程项目汇总合计值，二以下需要计算的所有
            /**
             * 需要汇总
             * 1.一、至本期累计完成百分比
             * 2.一、监理审核（元）
             * 3.农民工工伤保险费{[（一）+（二）+3+4]*费率}
             * 4.税金{[（一）+（二）+（三）]*费率}
             */
            $wherePorject=array(
                'payment_review_id' => $tableId,
            );
            $fields="id,payment_review_id,
                order_id,item_name,
                list_total_amount,
                last_approved_accumulated_amount,
                cumulative_completion_percent,
                report_amount_percent,
                report_construction_amount,
                approved_total_amount";

            //取出工程项目汇总所有数据
            $projectSummary=$this->PSummary_model->field($fields)->where($wherePorject)->select();
            /*echo "<pre>";
            var_dump($projectSummary);die;*/
            $approvedUsePercent=($projectSummary[0]["approved_total_amount"]+$projectSummary[0]["last_approved_accumulated_amount"])/$projectSummary[0]["list_total_amount"];

            //1	组织措施项目清单
            $wherea = array(
                'payment_review_id' => $tableId,
                'order_id' => '合计'
            );
            $orgml = $this->OMList_model->where($wherea)->find();
            /*echo "<pre>";
            var_dump($orgml);die;*/
            $item211["id"]= $projectSummary[15]["id"];
            $item211["report_construction_amount"]=$orgml['report_amount'];
            $item211["approved_total_amount"]=$orgml['approved_amount'];
            $item211["report_amount_percent"]=$item211['report_construction_amount']/$projectSummary[15]["list_total_amount"];
            $item211["cumulative_completion_percent"]=($item211['approved_total_amount']+$projectSummary[15]["last_approved_accumulated_amount"]) / $projectSummary[15]["list_total_amount"];
            $this->PSummary_model->save($item211);

            //（一）	整体措施项目清单（1+2）
            $item211["id"]=$projectSummary[14]["id"];
            $this->PSummary_model->save($item211);



            //5	农民工工伤保险费{[（一）+（二）+3+4]*费率}
            $item235["id"]= $projectSummary[21]["id"];
            $item235["report_construction_amount"]=($item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$projectSummary[19]["report_construction_amount"]
                    +$projectSummary[20]["report_construction_amount"])*0.114/100;
            $item235["approved_total_amount"]=$projectSummary[21]["list_total_amount"]*$approvedUsePercent-$projectSummary[21]["last_approved_accumulated_amount"];
            $item235["report_amount_percent"]=$item235['approved_total_amount']/$projectSummary[21]["list_total_amount"];
            $item235["cumulative_completion_percent"]=($item235['approved_total_amount']+$projectSummary[21]["last_approved_accumulated_amount"]) / $projectSummary[21]["list_total_amount"];
            $this->PSummary_model->save($item235);

            #(三)整体措施项目规费[3+4+5]
            $itemD345["id"]= $projectSummary[18]["id"];
            //本期完成
            $itemD345["report_construction_amount"]=$projectSummary[19]["report_construction_amount"]
                +$projectSummary[20]["report_construction_amount"]
                +$item235["report_construction_amount"];
            //监理审核
            $itemD345["approved_total_amount"]=$projectSummary[19]["approved_total_amount"]
                +$projectSummary[20]["approved_total_amount"]
                +$item235["approved_total_amount"];
            $itemD345["report_amount_percent"]=$itemD345["approved_total_amount"]/$projectSummary[18]["list_total_amount"];
            $itemD345["cumulative_completion_percent"]=($itemD345["approved_total_amount"]+$projectSummary[18]["last_approved_accumulated_amount"]) / $projectSummary[18]["list_total_amount"];
            $this->PSummary_model->save($itemD345);

            //（四）税金{[（一）+（二）+（三）]*费率}
            $itemD4["id"]= $projectSummary[22]["id"];
            //本期完成
            $itemD4["report_construction_amount"]=($item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$itemD345["report_construction_amount"])*3.577/100;
            //监理审核
            $itemD4["approved_total_amount"]=$projectSummary[22]["list_total_amount"]*$approvedUsePercent
                -$projectSummary[22]["last_approved_accumulated_amount"];
            $itemD4["report_amount_percent"]=$itemD4['approved_total_amount']/$projectSummary[22]["list_total_amount"];
            $itemD4["cumulative_completion_percent"]=($itemD4['approved_total_amount']+$projectSummary[22]["last_approved_accumulated_amount"]) / $projectSummary[22]["list_total_amount"];
            $this->PSummary_model->save($itemD4);
            //二、未纳入单位工程费的其他费用[（一）+（二）+（三）+（四）]
            $itemD2["id"]= $projectSummary[13]["id"];
            //本期完成
            $itemD2["report_construction_amount"]=$item211["report_construction_amount"]
                    +$projectSummary[17]["report_construction_amount"]
                    +$itemD345["report_construction_amount"]
                    +$itemD4["report_construction_amount"];
            //监理审核
            $itemD2["approved_total_amount"]=$item211["approved_total_amount"]
                +$projectSummary[17]["approved_total_amount"]
                +$itemD345["approved_total_amount"]
                +$itemD4["approved_total_amount"];
            $itemD2["report_amount_percent"]=$itemD2['approved_total_amount']/$projectSummary[13]["list_total_amount"];
            $itemD2["cumulative_completion_percent"]=($itemD2['approved_total_amount']+$projectSummary[13]["last_approved_accumulated_amount"]) / $projectSummary[13]["list_total_amount"];
            $this->PSummary_model->save($itemD2);

            //总报价[一+二]
            $itemZ["id"]= $projectSummary[23]["id"];
            //本期完成
            $itemZ["report_construction_amount"]=$projectSummary[0]["report_construction_amount"]
                +$itemD2["report_construction_amount"];
            //监理审核
            $itemZ["approved_total_amount"]=$projectSummary[0]["approved_total_amount"]
                +$itemD2["approved_total_amount"];
            $itemZ["report_amount_percent"]=$itemZ['approved_total_amount']/$projectSummary[23]["list_total_amount"];
            $itemZ["cumulative_completion_percent"]=($itemZ['approved_total_amount']+$projectSummary[23]["last_approved_accumulated_amount"]) / $projectSummary[23]["list_total_amount"];
            $this->PSummary_model->save($itemZ);
            //更新总报价(大写)：
            $itemZD["id"]= $projectSummary[24]["id"];
            $itemZD["item_name"]=$this->number2chinese($itemZ['report_construction_amount'], true, false);
            $this->PSummary_model->save($itemZD);

        }
		// 计算小计总价
		$fields=" SUM(last_approved_accumulated_amount) AS sum1,SUM(report_total_amount)AS sum2,SUM(approved_total_amount)AS sum3";
		$where = array(
				'payment_review_id'		=> $tableId,
				'is_publish'			=> '1',
				'order_id'				=>'六'
			);

		$field = "SUM(report_construction_amount) as report,SUM(approved_total_amount) as approved";
		$summary = $this->QPSummary_model->field($fields)->where($where)->find();
		$saveData3 = array(
				'last_approved_accumulated_amount'=>$summary['sum1']==NULL? 0: $summary['sum1'],
				'report_construction_amount'	=> $summary['sum2']==NULL? 0:$summary['sum2'],
				'approved_total_amount'			=> $summary['sum3']==NULL?0:$summary['sum3']
		);
		unset($fields);
		unset($where);
		unset($summary);

		$saveWhere = array(
			'payment_review_id'		=> $tableId,
			'order_id'				=> '一'
		);
		$this->PSummary_model->where($saveWhere)->save($saveData3);
		
		// 计算工程项目报价汇总 总计 
		$summaryInfo = $this->PSummary_model->field($field)->where("payment_review_id = " . $tableId ." AND order_id IN('一', '二')")->find();
		/*echo "<pre>";
		var_dump($summaryInfo);die;*/
		$saveData3 = array(
			'report_construction_amount'	=> !$summaryInfo || $summaryInfo['report'] == NULL ? 0 : $summaryInfo['report'],
			'approved_total_amount'			=> !$summaryInfo || $summaryInfo['approved'] == NULL ? 0 : $summaryInfo['approved']
		);
		unset($summaryInfo);
		$saveWhere = array(
			'payment_review_id'		=> $tableId,
			'item_name'				=> '总报价[一+二]'
		);
		$this->PSummary_model->where($saveWhere)->save($saveData3);
		
		// 计算项目工程报价 总计 大写
		$saveData3 = array(
			'item_name'	=> $this->number2chinese($saveData3['report_construction_amount'], true, false)
		);
		$saveWhere = array(
			'payment_review_id'		=> $tableId,
			'order_id'				=> array('like', '总报价%')
		);
		$this->PSummary_model->where($saveWhere)->save($saveData3);
		
		/**
		 * 计算单位工程报价 累计完成百分比
		 **/
		$sql = "UPDATE ".C('DB_PREFIX')."quoted_price_summary 
				SET cumulative_completion_percent = (last_approved_accumulated_amount + approved_total_amount) / list_total_amount 
				WHERE payment_review_id = ".$tableId." AND order_id NOT LIKE '总报价%'";
		$this->QPSummary_model->execute($sql);
		
		/**
		 * 工程项目报价汇总 - 组织措施项目清单
		 **/
		// 查询组织措施清单合计值信息
		$where = array(
			'payment_review_id'	=> $tableId,
			'order_id'			=> '合计',
			'is_publish'		=> '1'
		);
		$oml = $this->OMList_model->field("report_amount,approved_amount")->where($where)->find();
		$saveData = array(
			'report_construction_amount'=> $oml['report_amount'] != NULL ? $oml['report_amount'] : 0,
			'approved_total_amount'		=>$oml['report_amount'] != NULL ? $oml['approved_amount'] : 0
		);
		$saveWhere = "item_name = '整体措施项目清单（1+2）' OR item_name = '组织措施项目清单'";
		$this->PSummary_model->where($saveWhere)->save($saveData);
		
		/**
		 * 计算工程项目报价汇总表 至本期累计完成百分比与本期完成百分比
		 **/
		$sql = "UPDATE ".C('DB_PREFIX')."project_summary
				SET cumulative_completion_percent = (last_approved_accumulated_amount + approved_total_amount) / list_total_amount,
					report_amount_percent = approved_total_amount / list_total_amount
				WHERE payment_review_id = ".$tableId." AND order_id NOT LIKE '总报价%';";
		$this->PSummary_model->execute($sql);
		
		/**
		 * 更新主表信息
		 **/
		$this->updateData($tableId);
	}
	
	/**
	 * 更新主表 工程量清单信息
	 **/
	public function updateData($tableId){
		// 查询清单工程报价表总报价

        $where = array(
            'payment_review_id' => $tableId,
            'item_name'			=> '总报价[一+二]',
            'is_publish'		=> '1'
        );
        $price = $this->PSummary_model->field("report_construction_amount")->where($where)->find();


		// 保存数据
		$saveData = array(
			'id'			=> $tableId,
			'list_pricing'	=> $price['report_construction_amount']==NULL?0:$price['report_construction_amount'],
			'payables'		=> $price['report_construction_amount']==NULL?0.0:$price['report_construction_amount'] * 0.75,
			'amount_in_words'=> $this->number2chinese($price['report_construction_amount'] * 0.75, true, false)
		);
		$this->deal_model->save($saveData);
	}

	// 导入文件
	public function addPostFile(){
		$fileType = I("post.exceltype", '');
		$tableId = I("post.id", '');
		$result=true;
		if(!empty($_POST["attachment"])){
			
			if($fileType == 1){ // 技术措施项目清单及计价表__建筑工程
				$result= $this->importTec("attachment", $tableId, 1);
			} elseif($fileType == 2){ // 技术措施项目清单及计价表__安装工程	
				$result = $this->importTec("attachment", $tableId, 2);
			} elseif($fileType == 5){ // 组织措施项目（整体）清单及计
				$result = $this->importOml("attachment", $tableId);
			} elseif($fileType == 6){ // 工程形象进度完成情况
				$result = $this->importPProgress("attachment", $tableId);
			} elseif($fileType == 7){ // 分部分项工程量清单及计价表_建筑
				$result = $this->importTec("attachment", $tableId, 7);
			} elseif($fileType == 8){ // 分部分项工程量清单及计价表_安装
				$result = $this->importTec("attachment", $tableId, 8);
			} elseif($fileType == 3){ // 单位工程报价汇总表
				$result = $this->importQps("attachment", $tableId);
			} elseif($fileType == 4){ // 工程项目报价汇总表
				$result = $this->importPS("attachment", $tableId);
			}

			if($result){
				$this->success("导入成功！");
			}
			
			else{
				$this->error("导入失败,Excel格式不正确！");
			}
		}
	}
	
	/**
	 * 提交展示
	 **/
	public function publishs(){
		$fileType = I("post.exceltype", '');
		$sheet = I("post.sheet", '');
		$tableId = I("post.id", '');
		if($fileType == 1){ // 技术措施项目清单及计价表__建筑工程
			$where = array(
				'item_category'	=> '1',
				'construction_category'	=> '建筑工程',
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->TMList_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 2){ // 技术措施项目清单及计价表__安装工程	
			$where = array(
				'item_category'	=> '1',
				'construction_category'	=> '安装工程',
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->TMList_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 5){ // 组织措施项目（整体）清单及计
			$where = array(
				"payment_review_id"	=> $tableId
			);
			$this->OMList_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 6){ // 工程形象进度完成情况
			$where = array(
				"payment_review_id"	=> $tableId
			);
			$this->PProgress_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 7){ // 分部分项工程量清单及计价表_建筑
			$where = array(
				'item_category'	=> '2',
				'construction_category'	=> '建筑工程',
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->TMList_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 8){ // 分部分项工程量清单及计价表_安装
			$where = array(
				'item_category'	=> '2',
				'construction_category'	=> '安装工程',
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->TMList_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 3){ // 单位工程报价汇总表
			$where = array(
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->QPSummary_model->where($where)->save(array("is_publish" => 1));
		} elseif($fileType == 4){ // 工程项目报价汇总表
			$where = array(
				"position_name" => $sheet,
				"payment_review_id"	=> $tableId
			);
			$this->PSummary_model->where($where)->save(array("is_publish" => 1));
            $this->updateData($tableId);
		}
		$this->success("提交成功！");
	}
	
	// 引入导入文件
	private function requireExcel(){
		/*导入phpExcel核心类 SPAPP_PATH为存放phpexcel路径的定义，在入口文件index.php定义*/
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel.php';
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel5.php';// 用于其他低版本xls 
		require_once SPAPP_PATH.'Core/Library/Vendor/PHPExcel/PHPExcel/Writer/Excel2007.php';// 用于 excel-2007 格式  
	}
	
	/**
	 * 导入数据
	 * 技术措施项目清单及计价表__建筑工程 
	 * 技术措施项目清单及计价表__安装工程 
	 * 分部分项工程量清单及计价表_建筑工程
	 * 分部分项工程量清单及计价表_安装工程
	 **/
	public function importTec($file, $tableId, $type){
		$filePath = $_POST[$file];
		$this->requireExcel();
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 
		
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->refundData($file, $tableId);
				return; 
			} 
		} 
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		$dataArray = $PHPExcel->getSheet(0)->toArray();
		$datas = array(
			0 => "序号",
			1 => "项目编码",
			2 => "项目名称",
			3 => "项目特征描述",
			4 => "计量单位",
			5 => "清单工程量",
			6 => "上报完成工程量",
			7 => "至上月累计审核工程量",
			8 => "监理审核工程量",
			9 => "综合单价(元)",
			10 => "合价(元)",
		);
		$length = count($datas);
		$aa=true;
		for($i = 0;$i< $length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[3][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				//echo ("文件格式不一致，".$colName."执行了这里");
				break;
			}
		}
		if(!$aa){
			return false;
		}
		// 保存数组
		$savedata['payment_review_id']	= $tableId;
		if($type == '1'){
			$savedata['item_category'] = 1;
			$savedata['construction_category'] = '建筑工程';
		}
		if($type == '2'){
			$savedata['item_category'] = 1;
			$savedata['construction_category'] = '安装工程';
		}
		if($type == '7'){
			$savedata['item_category'] = 2;
			$savedata['construction_category'] = '建筑工程';
		}
		if($type == '8'){
			$savedata['item_category'] = 2;
			$savedata['construction_category'] = '安装工程';
		}
		for($i = 0; $i < count($sheetNames); $i++){
			// sheet页名称
			$savedata['position_name']	= $sheetNames[$i];
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得最大的列号
			//$allColumn = $currentSheet->getHighestColumn();
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			
			// 申报合价 与 监理合价
			$complete = 0;
			$approved = 0;
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 6; $currentRow <= $allRow - 2; $currentRow++){
				if(empty($currentSheet->getCell("B".$currentRow)->getValue())){
					continue;
				}
				$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getValue();
				$savedata['item_code']	= $currentSheet->getCell("B".$currentRow)->getValue();
				$savedata['item_name']	= $currentSheet->getCell("C".$currentRow)->getValue();
				$savedata['item_description']	= $currentSheet->getCell("D".$currentRow)->getValue();
				$savedata['measurement_unit']	= $currentSheet->getCell("E".$currentRow)->getValue();
				$savedata['inventory_workload']	= $currentSheet->getCell("F".$currentRow)->getValue() == "" ? 0 : $currentSheet->getCell("F".$currentRow)->getValue();
				$savedata['complete_workload']	= $currentSheet->getCell("G".$currentRow)->getValue();
				// 至上月累计审核工程量 数据库查询当前【申报类型】、【工程类型】、【专业名称】、【项目编码】 中的 【至上月累计审核工程量】 + 【监理审核工程量】
				// $savedata['last_month_accumulated_workload']	= $currentSheet->getCell("H".$currentRow)->getValue();
				$where = array(
					'item_category' => $savedata['item_category'],
					'construction_category' => $savedata['construction_category'],
					'position_name'	=> $savedata['position_name'],
					'item_code'		=> $savedata['item_code'],
					'is_publish'=>'1'
				);
				$result = $this->TMList_model->field("last_month_accumulated_workload as last,approved_workload")->where($where)->order("id DESC")->find();
				$savedata['last_month_accumulated_workload'] = $result ? ($result['last'] + $result['approved_workload']) : 0;//dump($savedata['last_month_accumulated_workload']);
				$savedata['approved_workload']	= $currentSheet->getCell("I".$currentRow)->getValue();
				$unit_price = $currentSheet->getCell("J".$currentRow)->getValue();
				$savedata['unit_price']	= $unit_price == NULL ? 0.00 : $unit_price;
				// 施工申报合价=上报完成工作量 * 综合单价
				$savedata['complete_total_value'] = $savedata['complete_workload'] * $savedata['unit_price'];
				$complete += $savedata['complete_total_value'];
				//$currentSheet->getCell("K".$currentRow)->getValue();
				// 监理审核合价=监理审核工作量 * 综合单价
				$savedata['approved_workload_total_value'] = $savedata['approved_workload'] * $savedata['unit_price'];
				$approved += $savedata['approved_workload_total_value'];
				//$currentSheet->getCell("L".$currentRow)->getValue();
				if($currentRow == $allRow - 2){
					unset($savedata['last_month_accumulated_workload']);
					unset($savedata['unit_price']);
					$savedata['complete_total_value'] = $complete;
					$savedata['approved_workload_total_value'] = $approved;
				}
				$this->TMList_model->add($savedata);
			}
		}
		
		// 导入完成 删除文件
		unlink($filePath);
		return true;
	}
	
	/*
	 * 导入数据
	 * 单位工程报价汇总表
	 **/
    /**
     * @param $file
     * @param $tableId
     * @return bool
     */
    public function importQps($file, $tableId){
		$filePath = $_POST[$file];
		$this->requireExcel();
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 
		
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->refundData($file, $tableId);
				return; 
			} 
		} 
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		$dataArray = $PHPExcel->getSheet(0)->toArray();
		/*echo "<pre>";
		var_dump($dataArray);die;*/
		$datas = array(
			0 => "",
			1 => "内容",
			2 => "报价合计(元)",
			3 => "累计完成百分比",
			4 => "至上期末累计完成",
			5 => "至上期末监理审核完成（元）",
			6 => "本期完成(元)",			
		);
		$length = count($datas);
		$aa=true;
		for($i = 0;$i< $length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[3][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				break;
			}
		}
		if(!$aa){
			return false;
		}		
		// 保存数组
		$savedata['payment_review_id']	= $tableId;
		for($i = 0; $i < count($sheetNames); $i++){
			// sheet页名称
			$savedata['position_name']	= $sheetNames[$i];
			//读取excel文件中的第i个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();

			// 用于分部分项、技术措施清单及计价 过滤条件构建
			$where = array(
				'payment_review_id'		=> $tableId,
				'item_category'			=> 1,
				'construction_category'	=> '建筑工程',
				'position_name'			=> $savedata['position_name'],
				'item_code'				=> '合计',
				'is_publish'			=>1
			);
            $fields="complete_total_value as complete,approved_workload_total_value as approved";
			$sum2=0.0;


			/**从第6行开始输出，因为excel表中第一行为列名*/
			for($currentRow = 6; $currentRow <= $allRow - 2; $currentRow++){
			    //取编号、内容、报价合计
				$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getValue();
                $savedata['item_name']	 = $currentSheet->getCell("B".$currentRow)->getValue();
				//$savedata['list_total_amount']	= $currentSheet->getCell("C".$currentRow)->getValue();
                $savedata['list_total_amount']	= $currentSheet->getCell("C".$currentRow)->getValue()==""?NULL:$currentSheet->getCell("C".$currentRow)->getValue();
                //取得至上期末监理审核完成
                //$savedata['last_approved_accumulated_amount'] = $currentSheet->getCell("F".$currentRow)->getValue();
				// 查询至上期末累计完成
				$subWhere = array(
					'payment_review_id'	=> array('neq', $tableId),
					'position_name'		=> $savedata['position_name'],
					'order_id'			=> $savedata['order_id'],
					'is_publish'		=>'1'
				);
				$lasttotal = $this->QPSummary_model
					->field("last_report_accumulated_amount as last_report,last_approved_accumulated_amount as last_approved,report_total_amount,approved_total_amount")
					->where($subWhere)
					->order("id DESC")
					->find();

                if($savedata['list_total_amount']==NULL){
                    $savedata['last_report_accumulated_amount']	= NULL;
                    $savedata['last_approved_accumulated_amount'] = NULL;
                    $savedata['cumulative_completion_percent'] = NULL;
                } else{
                    $savedata['last_report_accumulated_amount']	= $lasttotal ? $lasttotal['last_report'] + $lasttotal['report_total_amount'] : 0;
                    $savedata['last_approved_accumulated_amount'] = $lasttotal ? $lasttotal['last_approved'] + $lasttotal['approved_total_amount'] : 0;
                    
                }

				//计算分部分项工程量清单
				if($currentRow == 6){
				    //  一、分部分项工程量清单
                    // 本期 建筑工程
                    $where["item_category"]=2;
                    $where["construction_category"]='建筑工程';
					$thisbuild = $this->TMList_model->field($fields)->where($where)->find();
					$savedata['report_construction_amount'] = $thisbuild ? $thisbuild['complete'] : 0;
					$savedata['approved_construction_amount'] = $thisbuild ? $thisbuild['approved'] : 0;
					// 查询 安装工程
					$where['construction_category'] = '安装工程';
					$thisinstall = $this->TMList_model->field($fields)->where($where)->find();
					$savedata['report_installation_amount'] = $thisinstall ? $thisinstall['complete'] : 0;
					$savedata['approved_installation_amount'] = $thisinstall ? $thisinstall['approved'] : 0;
					// 本期总计
					$savedata['report_total_amount'] = $savedata['report_construction_amount'] + $savedata['report_installation_amount'];
					$savedata['approved_total_amount'] = $savedata['approved_construction_amount'] + $savedata['approved_installation_amount'];
				} elseif($currentRow == 7){
				    //  二、措施项目清单（1+2）
                    // 本期 建筑工程
                    $where["item_category"]=1;
                    $where["construction_category"]='建筑工程';
                    $thisbuild= $this->TMList_model->field($fields)->where($where)->find();
                    $savedata['report_construction_amount'] = $thisbuild ? $thisbuild['complete'] : 0;
                    $savedata['approved_construction_amount'] = $thisbuild ? $thisbuild['approved'] : 0;

                    //本期 安装工程
                    $where["construction_category"]='安装工程';
                    $thisinstall= $this->TMList_model->field($fields)->where($where)->find();
                    $savedata['report_installation_amount'] = $thisinstall ? $thisinstall['complete'] : 0;
                    $savedata['approved_installation_amount'] = $thisinstall ? $thisinstall['approved'] : 0;
                    // 本期总计
                    $savedata['report_total_amount'] = $savedata['report_construction_amount'] + $savedata['report_installation_amount'];
                    $savedata['approved_total_amount'] = $savedata['approved_construction_amount'] + $savedata['approved_installation_amount'];

				} elseif($currentRow == 8){
				    //  二.1、组织措施项目清单
                    // 本期建筑
					$savedata['report_construction_amount'] = NULL;
					$savedata['approved_construction_amount'] = NULL;
					// 本期安装
					$savedata['report_installation_amount'] = NULL;
					$savedata['approved_installation_amount'] = NULL;
					$savedata['report_total_amount'] = NULL;
					$savedata['approved_total_amount'] = NULL;
					$savedata['list_total_amount']	= NULL;
				} elseif($currentRow == 9){
				    //  二.2、技术措施项目清单
                    // 本期 建筑工程
                    $where["item_category"]=1;
                    $where["construction_category"]='建筑工程';
                    $thisbuild= $this->TMList_model->field($fields)->where($where)->find();
					$savedata['report_construction_amount'] = $thisbuild ? $thisbuild['complete'] : 0;
					$savedata['approved_construction_amount'] = $thisbuild ? $thisbuild['approved'] : 0;

					//本期 安装工程
                    $where["construction_category"]='安装工程';
                    $thisinstall= $this->TMList_model->field($fields)->where($where)->find();
					$savedata['report_installation_amount'] = $thisinstall ? $thisinstall['complete'] : 0;
					$savedata['approved_installation_amount'] = $thisinstall ? $thisinstall['approved'] : 0;
					// 本期总计
					$savedata['report_total_amount'] = $savedata['report_construction_amount'] + $savedata['report_installation_amount'];
					$savedata['approved_total_amount'] = $savedata['approved_construction_amount'] + $savedata['approved_installation_amount'];
				}elseif($currentRow==12){

				    //追加排污费公式计算
				    $where = array(
				    	'payment_review_id'		=> $savedata['payment_review_id'],
                        'position_name'			=> $savedata['position_name'],
                        'order_id'               => "一"
				    );
				    $field = "list_total_amount,report_construction_amount,report_construction_amount,sum(report_total_amount) report,sum(approved_total_amount) approved,cumulative_completion_percent";
				    $sumarry12 = $this->QPSummary_model->field($field)->where($where)->find();
				    //计算排污费、社保费、公积金 施工本期合计
				    $savedata['report_total_amount'] = $savedata['list_total_amount']*($sumarry12['report_construction_amount']/$sumarry12['list_total_amount']);
				    //计算排污费、社保费、公积金 本期监理审核合计
				    $savedata['approved_total_amount'] = $savedata['list_total_amount']*$sumarry12['cumulative_completion_percent']/100-$savedata['last_approved_accumulated_amount'];

                } elseif($currentRow==14){

                    //释放过滤条件变量
                    unset($where);
                    //  四.5、民工工伤保险费[（一+二+三+3+4）*费率]0.114%
                    $where = array(
                        'payment_review_id'		=> $savedata['payment_review_id'],
                        'position_name'			=> $savedata['position_name'],
                        '_string'				=> "order_id IN('一','二','三','3','4')"
                    );
                    $fields="sum(report_total_amount) report,sum(approved_total_amount) approved";

                    $sumarry45 = $this->QPSummary_model->field($fields)->where($where)->find();
                    $savedata['report_total_amount'] = $sumarry45['report']*0.114/100;
                    //先计算分部分项工程量清单累计完成百分比，即是费率
                    $wheres = array(
                    	'payment_review_id'		=> $savedata['payment_review_id'],
                        'position_name'			=> $savedata['position_name'],
                        'order_id'               => "一"
                    );
                    $fieldss = "last_approved_accumulated_amount,approved_total_amount AS approved,cumulative_completion_percent";
                    $sumarry46 = $this->QPSummary_model->field($fieldss)->where($wheres)->find();
                    //民工工伤保险监理审核合计计算公式
                    $savedata['approved_total_amount'] = ($savedata['list_total_amount']*$sumarry46['cumulative_completion_percent']/100)-$savedata['last_approved_accumulated_amount'];

                    //  四、规费[3+4+5]
                    $where['_string'] = "order_id IN('3','4')";
                    $sumarry4=$this->QPSummary_model->field($fields)->where($where)->find();
                    $GuiFei["report_total_amount"]=$sumarry4["report"]+$savedata['report_total_amount'];
                    $GuiFei['approved_total_amount']=$sumarry4["approved"]+$savedata['approved_total_amount'];
                    //更新规费
                    $where["_string"] = "order_id='四'";
                    $this->QPSummary_model->where($where)->save($GuiFei);
                }
                elseif($currentRow==15){
                    //  五	税金[（一+二+三+四）*费率]3.577%
                    $where["_string"] = "order_id IN('一','二','三','四')";
                    $sumarry5 = $this->QPSummary_model->field($fields)->where($where)->find();
                    $savedata['report_total_amount'] = $sumarry5['report']*3.577/100;
                    
                    //本期监理审核合计=税金报价合计*费率-至上期末监理审核完成
                    $wheres = array(
                    	'payment_review_id'		=> $savedata['payment_review_id'],
                        'position_name'			=> $savedata['position_name'],
                        'order_id'               => "一"
                    );
                    $fieldss = "last_approved_accumulated_amount,sum(approved_total_amount) approved,cumulative_completion_percent";
                    $sumarry15 = $this->QPSummary_model->field($fieldss)->where($wheres)->find();
                    $savedata['approved_total_amount'] = $savedata['list_total_amount']*$sumarry15['cumulative_completion_percent']/100-$savedata['last_approved_accumulated_amount'];
                }
				elseif($currentRow == $allRow - 3){
					//总报价（一+二+三+四+五）
					$fields="SUM(last_approved_accumulated_amount) as sum1,SUM(report_total_amount) as sum2,SUM(approved_total_amount) as sum3";
                    $where["_string"]= "order_id IN('一','二','三','四','五')";
					$sumarry = $this->QPSummary_model->field($fields)->where($where)->find();
					$savedata['report_total_amount'] = $sumarry['sum2']==NULL?0:$sumarry['sum2'];
					$savedata['approved_total_amount'] = $sumarry['sum3']==NULL?0:$sumarry['sum3'];
					$savedata['last_approved_accumulated_amount'] = $sumarry['sum1']==NULL?0:$sumarry['sum1'];
					$savedata['cumulative_completion_percent'] = ($savedata['last_approved_accumulated_amount'] +$savedata['approved_total_amount'])/$savedata['list_total_amount'];
					$sum2=$savedata['report_total_amount'];
				}elseif($currentRow == $allRow - 2){
					unset($savedata);

					$savedata['payment_review_id']	= $tableId;
					$savedata['item_name']	= $this->number2chinese($sum2, true, false);
					$savedata['position_name'] = $sheetNames[$i];
					$savedata['order_id'] = $currentSheet->getCell("A".$currentRow)->getValue();
					$this->QPSummary_model->add($savedata);
					continue;
				} else {
					// 本期建筑
					$savedata['report_construction_amount'] = NULL;
					$savedata['approved_construction_amount'] = NULL;
					// 本期安装
					$savedata['report_installation_amount'] = NULL;
					$savedata['approved_installation_amount'] = NULL;
					// 本期总计
					$valueG = $currentSheet->getCell("G".$currentRow)->getCalculatedValue();
					$savedata['report_total_amount'] = $valueG ? $valueG : 0;
					$valueJ = $currentSheet->getCell("J".$currentRow)->getCalculatedValue();
					$savedata['approved_total_amount'] = $valueJ ? $valueJ : 0;
				}

				//需要整理着一块了 ，前面的完了
				$savedata['cumulative_completion_percent'] = (($savedata['last_approved_accumulated_amount'] + $savedata['approved_total_amount'])/$savedata['list_total_amount']) * 100;

				// 保存数据
				$this->QPSummary_model->add($savedata);
			}

		}

		// 导入完成 删除文件
		unlink($filePath);
		return true;
	}
	
	/*
	 * 导入数据
	 * 工程项目报价汇总表  
	 **/
	public function importPS($file, $tableId){
		$filePath = $_POST[$file];
		$this->requireExcel();
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 
		
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->refundData($file, $tableId);
				return; 
			} 
		}
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		$dataArray = $PHPExcel->getSheet(0)->toArray();
		/*echo "<pre>";
		var_dump($dataArray);die;*/
		$datas = array(
			0 => "序号",
			1 => "内容",
			2 => "报价(元)",
			3 => "至上期累计完成工程量（元）",
			4 => "至本期累计完成百分比",
			5 => "本期完成百分比",
			6 => "本期完成(元)",
			7 => "监理审核（元）"
		);
		$aa = true;
		$length = count($datas);
		for($i=0;$i<$length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[2][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				break;
			}
		}
		if(!$aa){
			return false;
		}
		// 保存数组
		$savedata['payment_review_id']	= $tableId;
		$sumreport=0.0;
		for($i = 0; $i < count($sheetNames); $i++){
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			$allColumn = $currentSheet->getHighestColumn();

			//取单位工程，累计审核完成、本期上报、本期审核，已经提交的

			$fields="SUM(last_approved_accumulated_amount) as sum1,SUM(report_total_amount) as sum2,SUM(approved_total_amount) as sum3";
			$where = array(
				'payment_review_id'		=> $tableId,
				'is_publish'			=> '1',
				'order_id'				=>'六'
			);
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 4; $currentRow <= $allRow - 3; $currentRow++){
				$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getValue();
				$savedata['item_name']	= $currentSheet->getCell("B".$currentRow)->getValue();
				//$savedata['list_total_amount']	= $currentSheet->getCell("C".$currentRow)->getCalculatedValue();
                $savedata['list_total_amount']	= $currentSheet->getCell("C".$currentRow)->getValue()==""?NULL:$currentSheet->getCell("C".$currentRow)->getValue();
				// 查询至上期累计完成工作量
				$subWhere = array(
					'payment_review_id'	=> array('neq', $tableId),
					'item_name'		=> $savedata['item_name'],
					'order_id'			=> $savedata['order_id'],
					'is_publish'		=>'1'
				);
				$lasttotal = $this->PSummary_model
					->field("last_approved_accumulated_amount as last_approved,approved_total_amount")
					->where($subWhere)
					->order("id DESC")
					->find();

                if($savedata['list_total_amount']==NULL){
                    $savedata['last_approved_accumulated_amount'] = NULL;
                    $savedata['cumulative_completion_percent'] = NULL;
                } else{
                    $savedata['last_approved_accumulated_amount'] = $lasttotal ? $lasttotal['last_approved'] + $lasttotal['approved_total_amount'] : 0;
                    
                }

                //   4-16行数据汇总与单位工程报价汇总表，取已发布数据
				if($currentRow==4){
					$summaryInfo = $this->QPSummary_model->field($fields)->where($where)->find();
					//至上期累计完成工程量(元)
					$savedata['last_approved_accumulated_amount']	= $summaryInfo['sum1'] != NULL ? $summaryInfo['sum1'] : 0;
					//本期完成
					$savedata['report_construction_amount']	=  $summaryInfo['sum2'] != NULL ? $summaryInfo['sum2'] : 0;
					//监理审核
					$savedata['approved_total_amount']	= $summaryInfo['sum3'] != NULL ? $summaryInfo['sum3'] : 0;
					//至本期累计完成百分比
					$savedata['cumulative_completion_percent']	= ($savedata['last_approved_accumulated_amount']+$savedata['report_construction_amount'])/$savedata['list_total_amount'];
					//本期完成百分比
					$savedata['report_amount_percent']	= $savedata['report_construction_amount']/$savedata['list_total_amount'];

				}
				elseif($currentRow >= 5&&$currentRow < 17){
					//本期完成，取单元工程项目报价汇总
					$where['position_name'] = $savedata['item_name'];
                    $fields = "last_approved_accumulated_amount,report_total_amount,approved_total_amount";
					$summaryInfo = $this->QPSummary_model->field($fields)->where($where)->find();

					//至上期累计完成工程量(元)
					$savedata['last_approved_accumulated_amount']	= $summaryInfo['last_approved_accumulated_amount'] != NULL ? $summaryInfo['last_approved_accumulated_amount'] : 0;
					//本期完成
					$savedata['report_construction_amount']	=  $summaryInfo['report_total_amount'] != NULL ? $summaryInfo['report_total_amount'] : 0;
					//监理审核
					$savedata['approved_total_amount']	= $summaryInfo['approved_total_amount'] != NULL ? $summaryInfo['approved_total_amount'] : 0;
					//至本期累计完成百分比
					$savedata['cumulative_completion_percent']	= ($savedata['last_approved_accumulated_amount']+$savedata['approved_total_amount'])/$savedata['list_total_amount'];
					//本期完成百分比
					$savedata['report_amount_percent']	= $savedata['approved_total_amount']/$savedata['list_total_amount'];
				}
				elseif($currentRow==19){
					//组织措施清单
					//本期完成，取组织措施项目清单
					$where = array(
						'payment_review_id'		=> $tableId,
						'is_publish'			=> '1',
						'order_id'				=>'合计'
					);                    
					$summaryInfo = $this->OMList_model->where($where)->find();
					

					//至上期累计完成工程量(元)
					$savedata['last_approved_accumulated_amount']	= $summaryInfo['last_approved_accumulated_amount'] != NULL ? $summaryInfo['last_approved_accumulated_amount'] : 0;
					//本期完成
					$savedata['report_construction_amount']	=  $summaryInfo['report_amount'] != NULL ? $summaryInfo['report_amount'] : 0;
					//监理审核
					$savedata['approved_total_amount']	= $summaryInfo['approved_amount'] != NULL ? $summaryInfo['approved_amount'] : 0;
					//至本期累计完成百分比
					$savedata['cumulative_completion_percent']	= ($savedata['last_month_accumulated_pay']+$savedata['approved_total_amount'])/$savedata['list_total_amount'];
					//本期完成百分比
					$savedata['report_amount_percent']	= $savedata['approved_total_amount']/$savedata['list_total_amount'];

                    //  更新 	整体措施项目清单(1+2) row=18
                    $field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3,sum(list_total_amount) as sum4";
                    $where["_string"]="item_name IN ('组织措施项目清单','技术措施项目清单')";
                    $summary345=$this->PSummary_model->field($field)->where($where)->find();

                    //至上期累计完成工程量(元)
                    $upData['last_approved_accumulated_amount']	= $savedata['last_approved_accumulated_amount']+$summary345['sum1'];
                    //本期完成
                    $upData["report_construction_amount"]=$savedata['report_construction_amount']+$summary345['sum2'];
                    //监理审核
                    $upData['approved_total_amount']	= $savedata['approved_total_amount']+$summary345['sum3'];
                    //至本期累计完成百分比
                    $upData['cumulative_completion_percent']	= ($upData['last_approved_accumulated_amount']+$upData['approved_total_amount'])/($savedata['list_total_amount']+$summary345['sum4']);
                    //本期完成百分比
                    $upData['report_amount_percent']	= ($savedata['approved_total_amount']+$summary345['sum2'])/($savedata['list_total_amount']+$summary345['sum4']);

                    $upWhere = array(
                        'payment_review_id'		=> $tableId,
                        'item_name'				=> "整体措施项目清单（1+2）"
                    );
                    $this->PSummary_model->where($upWhere)->save($upData);
				}elseif($currentRow==25){
				    unset($where);
				    unset($fields);
				    //  5	农民工工伤保险费{[（一）+（二）+3+4]*费率}

                    //需要追加监理审核计算
                    $field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3";
                    $where = array(
                        'payment_review_id'		=> $tableId,
                        '_string'				=> "item_name IN ('整体措施项目清单（1+2）','整体其他项目清单','排污费、社保费、公积金','危险作业意外伤害保险费')"
                    );
                    $summaryInfo=$this->PSummary_model->field($field)->where($where)->find();
                    //至上期累计完成工程量(元)
                    //$savedata['last_approved_accumulated_amount']	= $summaryInfo['sum1'] != NULL ? $summaryInfo['sum1'] : 0;
                    //本期完成
                    $savedata['report_construction_amount']	=  $summaryInfo['sum2'] != NULL ? $summaryInfo['sum2']*0.114/100 : 0;
                    //监理审核
                    //追加农民工工伤保险费监理审核计算公式
                    //$savedata['approved_total_amount']	= $summaryInfo['sum3'] != NULL ? $summaryInfo['sum3'] : 0;
                    $wheres = array(
                    	'payment_review_id'		=> $tableId,
                    	'order_id' => '一'
                    );
                    $field = "list_total_amount,last_approved_accumulated_amount,cumulative_completion_percent,approved_total_amount";
                    $sumarry25 = $summaryInfo=$this->PSummary_model->field($field)->where($wheres)->find();

                    $savedata['approved_total_amount'] = $sumarry25['approved_total_amount']==NULL?0:$savedata['list_total_amount']*(($sumarry25['approved_total_amount']+$sumarry25['last_approved_accumulated_amount'])/$sumarry25['list_total_amount'])-$savedata['last_approved_accumulated_amount'];
                    //至本期累计完成百分比
                    $savedata['cumulative_completion_percent']	= ($savedata['last_approved_accumulated_amount']+$savedata['approved_total_amount'])/$savedata['list_total_amount'];
                    //本期完成百分比
                    $savedata['report_amount_percent']	= $savedata['approved_total_amount']/$savedata['list_total_amount'];

                    //  更新 （三）	整体措施项目规费[3+4+5] row=22
                    $field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3,sum(list_total_amount) as sum4";
                    $where["_string"]="item_name IN ('排污费、社保费、公积金','危险作业意外伤害保险费')";
                    $summary345=$this->PSummary_model->field($field)->where($where)->find();

                    //至上期累计完成工程量(元)
                    $upData['last_approved_accumulated_amount']	= $savedata['last_approved_accumulated_amount']+$summary345['sum1'];
                    //本期完成
                    $upData["report_construction_amount"]=$savedata['report_construction_amount']+$summary345['sum2'];
                    //监理审核
                    $upData['approved_total_amount']	= $savedata['approved_total_amount']+$summary345['sum3'];
                    //至本期累计完成百分比
                    $upData['cumulative_completion_percent']	= ($upData['last_approved_accumulated_amount']+$upData['approved_total_amount'])/($savedata['list_total_amount']+$summary345['sum4']);
                    //本期完成百分比
                    $upData['report_amount_percent']	= ($savedata['approved_total_amount']+$summary345['sum2'])/($savedata['list_total_amount']+$summary345['sum4']);

                    $upWhere = array(
                        'payment_review_id'		=> $tableId,
                        'item_name'				=> "整体措施项目规费[3+4+5]"
                    );
                    $this->PSummary_model->where($upWhere)->save($upData);



                }
                elseif($currentRow==26){
                    //  （四）	税金{[（一）+（二）+（三）]*费率}
                    $field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3";
                    $where = array(
                        'payment_review_id'		=> $tableId,
                        '_string'				=> "order_id IN ('（一）','（二）','（三）')"
                    );
                    $summaryInfo=$this->PSummary_model->field($field)->where($where)->find();
                    //至上期累计完成工程量(元)
                    //$savedata['last_approved_accumulated_amount']	= $summaryInfo['sum1'] != NULL ? $summaryInfo['sum1'] : 0;
                    //本期完成
                    $savedata['report_construction_amount']	=  $summaryInfo['sum2'] != NULL ? $summaryInfo['sum2']*3.577/100 : 0;

                    //追加监理审核计算
                    //监理审核
                    //$savedata['approved_total_amount']	= $summaryInfo['sum3'] != NULL ? $summaryInfo['sum3'] : 0;
                    $wheres = array(
                    	'payment_review_id'		=> $tableId,
                    	'order_id' => '一'
                    );
                    $field = "list_total_amount,last_approved_accumulated_amount,cumulative_completion_percent,approved_total_amount";
                    $sumarry25 = $summaryInfo=$this->PSummary_model->field($field)->where($wheres)->find();
                    //echo "<pre>";
                    //var_dump($sumarry25);
                    $savedata['approved_total_amount'] = $sumarry25['approved_total_amount']==NULL?0:$savedata['list_total_amount']*(($sumarry25['approved_total_amount']+$sumarry25['last_approved_accumulated_amount'])/$sumarry25['list_total_amount'])-$savedata['last_approved_accumulated_amount'];                    
                    //至本期累计完成百分比
                    $savedata['cumulative_completion_percent']	= ($savedata['last_approved_accumulated_amount']+$savedata['approved_total_amount'])/$savedata['list_total_amount'];
                    //本期完成百分比
                    $savedata['report_amount_percent']	= $savedata['approved_total_amount']/$savedata['list_total_amount'];



                    //  更新 二	未纳入单位工程费的其他费用[（一）+（二）+（三）+（四）]
                    $field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3,sum(list_total_amount) as sum4";
                    $where["_string"]="order_id IN ('（一）','（二）','（三）')";

                    $summary345=$this->PSummary_model->field($field)->where($where)->find();

                    //至上期累计完成工程量(元)
                    $upData['last_approved_accumulated_amount']	= $savedata['last_approved_accumulated_amount']+$summary345['sum1'];
                    //本期完成
                    $upData["report_construction_amount"]=$savedata['report_construction_amount']+$summary345['sum2'];
                    //监理审核
                    $upData['approved_total_amount']	= $savedata['approved_total_amount']+$summary345['sum3'];
                    //至本期累计完成百分比
                    $upData['cumulative_completion_percent']	= ($upData['last_approved_accumulated_amount']+$upData['approved_total_amount'])/($savedata['list_total_amount']+$summary345['sum4']);
                    //本期完成百分比
                    $upData['report_amount_percent']	= ($savedata['approved_total_amount']+$summary345['sum3'])/($savedata['list_total_amount']+$summary345['sum4']);

                    $upWhere = array(
                        'payment_review_id'		=> $tableId,
                        'order_id'				=> "二"
                    );
                    $this->PSummary_model->where($upWhere)->save($upData);

                }
				elseif($currentRow==27){
					//总报价（一+二）
					$field="sum(last_approved_accumulated_amount) as sum1,sum(report_construction_amount) as sum2,sum(approved_total_amount)as sum3";
					$where = array(
						'payment_review_id'		=> $tableId,
						'_string'				=> "order_id IN('一','二')"
					);

					$summaryInfo = $this->PSummary_model->field($field)->where($where)->find();

					//至上期累计完成工程量(元)
					$savedata['last_approved_accumulated_amount']	= $summaryInfo['sum1'] != NULL ? $summaryInfo['sum1'] : 0;
					//本期完成
					$savedata['report_construction_amount']	=  $summaryInfo['sum2'] != NULL ? $summaryInfo['sum2'] : 0;
					//监理审核
					$savedata['approved_total_amount']	= $summaryInfo['sum3'] != NULL ? $summaryInfo['sum3'] : 0;
					//至本期累计完成百分比
					$savedata['cumulative_completion_percent']	= ($savedata['last_approved_accumulated_amount']+$savedata['approved_total_amount'])/$savedata['list_total_amount'];
					//本期完成百分比
					$savedata['report_amount_percent']	= $savedata['approved_total_amount']/$savedata['list_total_amount'];
					$sumreport=$savedata['report_construction_amount']	;
				}
				elseif($currentRow==28){
					//总报价（大写）
					unset($savedata);
					$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getCalculatedValue();
					$savedata['payment_review_id']	= $tableId;
					$savedata['item_name']	= $this->number2chinese($sumreport, true, false);
					$this->PSummary_model->add($savedata);
					continue;
				}
				else{
					//至上期累计完成工程量(元)
					$savedata['last_approved_accumulated_amount']	= $currentSheet->getCell("D".$currentRow)->getCalculatedValue();
					//至本期累计完成百分比
					$savedata['cumulative_completion_percent']	= $currentSheet->getCell("E".$currentRow)->getCalculatedValue();
					//本期完成百分比
					$savedata['report_amount_percent']	= $currentSheet->getCell("F".$currentRow)->getCalculatedValue();
					//本期完成
					$savedata['report_construction_amount']	= $currentSheet->getCell("G".$currentRow)->getCalculatedValue();
					//监理审核
					$savedata['approved_total_amount']	= $currentSheet->getCell("H".$currentRow)->getCalculatedValue();
				}
				// 保存数据
				$this->PSummary_model->add($savedata);
			}
		}
		/**
		 * 更新主表信息
		 **/
		//$this->updateData($tableId);
		
		// 导入完成 删除文件
		unlink($filePath);
		return true;
	}
	
	/*
	 * 导入数据
	 * 组织措施项目（整体）清单及计价表
	 **/
	public function importOml($file, $tableId){
		$filePath = $_POST[$file];
		$this->requireExcel();
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 
		
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->refundData($file, $tableId);
				return; 
			} 
		} 
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		$dataArray = $PHPExcel->getSheet(0)->toArray();

		$datas = array(
			0 => "序号",
			1 => "项目名称",
			2 => "单位",
			3 => "数量",
			4 => "金额(元)",
			5 => "至上期累计支付（元）",
			6 => "本期上报金额",
			7 => "监理审核",
			8 => "备注"			
		);
		$length = count($datas);
		$aa=true;
		for($i = 0;$i< $length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[2][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				break;
			}
		}
		if(!$aa){
			return false;
		}
		// 保存数组
		$savedata['payment_review_id']	= $tableId;
		for($i = 0; $i < count($sheetNames); $i++){
			// sheet页名称
			$savedata['position_name']	= $sheetNames[$i];
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			$total1 = 0;$total2 = 0;$total3 = 0;$total4 = 0;
			for($currentRow = 4; $currentRow <= $allRow - 2; $currentRow++){
				$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getValue();
				$savedata['item_name']	= $currentSheet->getCell("B".$currentRow)->getCalculatedValue();
				$savedata['measurement_unit']	= $currentSheet->getCell("C".$currentRow)->getCalculatedValue();
				$savedata['list_quantity']	= $currentSheet->getCell("D".$currentRow)->getCalculatedValue();
				if($currentRow == $allRow - 2){
					$savedata['list_amount'] = $total1;
					$savedata['last_month_accumulated_pay'] = $total2;
					$savedata['report_amount'] = $total3;
					$savedata['approved_amount'] = $total4;
				} else {
					$valueE = $currentSheet->getCell("E".$currentRow)->getCalculatedValue();
					$savedata['list_amount'] = $valueE == '' ? 0 : $valueE;
					$total1 += $savedata['list_amount'];
					// 查询上期累计支付
					$where = array(
						'payment_review_id'	=> array('neq', $tableId),
						'order_id'			=> $savedata['order_id']
					);
					$result = $this->OMList_model->field('last_month_accumulated_pay,approved_amount')->where($where)->order("id DESC")->find();
					$savedata['last_month_accumulated_pay']	= $result ? ($result['last_month_accumulated_pay'] + $result['approved_amount']) : 0;
					$total2 += $savedata['last_month_accumulated_pay'];
					$valueG = $currentSheet->getCell("G".$currentRow)->getCalculatedValue();
					$savedata['report_amount']	= $valueG == '' ? 0 : $valueG;
					$total3 += $savedata['report_amount'];
					$valueH = $currentSheet->getCell("H".$currentRow)->getCalculatedValue();
					$savedata['approved_amount'] = $valueH == '' ? 0 : $valueH;
					$total4 += $savedata['approved_amount'];
				}
				$savedata['remark']	= $currentSheet->getCell("I".$currentRow)->getCalculatedValue();
				// 保存数据
				$this->OMList_model->add($savedata);
			}
		}
		// 统计合计值
		$field = "";
		
		
		
		
		// 导入完成 删除文件
		unlink($filePath);
		return true;
	}
	/**
     * 修改状态为 发布
     */
    public function publish(){
		$param = $this->getParam();
		$url = U($param['m'].'/'.($param['fun'] != NULL ? $param['fun'] : 'index'));
        $id = I('get.id', 0, 'intval');
        if(!$id){
            $this->error("请选择要发布的数据！");
        }
        $data = array(
            'id'	=> $id,
            'is_publish' => 1
        );
        if ($this->deal_model->save($data) !== false) {
        	$this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'table_id' => $id))->save(array('add_time' => date('Y-m-d H:m:s')));
            $this->success("发布成功！", $url);
        } else {
            $this->error("发布失败！");
        }
    }
	/*
	 * 导入数据
	 * 工程形象进度完成情况 
	 **/
	public function importPProgress($file, $tableId){
		$filePath = $_POST[$file];
		$this->requireExcel();
		$PHPExcel = new \PHPExcel();//实例化，一定要注意命名空间的问题加\ 
		
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new \PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($filePath)){ 
			$PHPReader = new \PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($filePath)){ 
				$this->refundData($file, $tableId);
				return;
			} 
		} 
		//不需要读取整个Excel文件而获取所有工作表数组的函数
		$sheetNames  = $PHPReader->listWorksheetNames($filePath);
		$PHPExcel = $PHPReader->load($filePath);
		$dataArray = $PHPExcel->getSheet(0)->toArray();
		/*echo "<pre>";
		var_dump($dataArray);die;*/
		$datas = array(
			0 => "序号",
			1 => "单位项目",
			2 => "施工完成情况",
			3 => "监理审核情况"
		);
		$length = count($datas);
		$aa = true;
		for($i=0;$i<$length;$i++){
			$colName =str_replace(" ","",str_replace("\n", "", $dataArray[1][$i]));
			if($datas[$i] != $colName){
				$aa = false;
				break;
			}
		}
		if(!$aa){
			return false;
		}
		// 保存数组
		$savedata['payment_review_id']	= $tableId;
		for($i = 0; $i < count($sheetNames); $i++){
			// sheet页名称
			$savedata['position_name']	= $sheetNames[$i];
			//读取excel文件中的第一个工作表 
			$currentSheet = $PHPExcel->getSheet($i);
			//取得一共有多少行
			$allRow = $currentSheet->getHighestRow();
			/**从第二行开始输出，因为excel表中第一行为列名*/ 
			for($currentRow = 3; $currentRow <= $allRow - 2; $currentRow++){
				$savedata['order_id']	= $currentSheet->getCell("A".$currentRow)->getValue();
				$savedata['item_name']	= $currentSheet->getCell("B".$currentRow)->getValue();
				$savedata['complete_workload']	= $currentSheet->getCell("C".$currentRow)->getValue();
				$savedata['approved_workload']	= $currentSheet->getCell("D".$currentRow)->getValue();
				
				// 保存数据
				$this->PProgress_model->add($savedata);
			}
		}
		// 导入完成 删除文件
		unlink($filePath);
		return true;
	}
	
	/**
	 * 导入数据失败 删除插入数据
	 **/
	private function refundData($file, $tableId){
		// 删除主表数据
		$this->deal_model->where(array('id' => $tableId))->delete();
		// 删除审批历史数据
		$this->auditHistoryModel->where(array(
			'function'		=> $this->function,
			'subfunction'	=> $this->subfunction,
			'table_id'		=> $tableId
		))->delete();
		// 删除技术措施 以及 分部分项工程量 导入数据
		$where = array('payment_review_id' => $tableId);
		$this->TMList_model->where($where)->delete();
		// 单位工程报价汇总
		$this->QPSummary_model->where($where)->delete();
		// 组织措施项目(整体)清单及计价
		$this->OMList_model->where($where)->delete();
		// 工程进度完成情况
		$this->PProgress_model->where($where)->delete();
		// 工程项目报价汇总表
		$this->PSummary_model->where($where)->delete();
		
		// 页面输出错误信息
		$this->error("EXCEL文件【".$_POST[$file.'_name']."】不可读取！");
	}
	
	/**
     *  删除 
     */
	public function delete(){
	    $id = I('get.id', 0, 'intval');
		if(!$id){
			$this->error("请选择要删除的数据！");
		}
		$data = array(
			'id'	=> $id,
			'is_deleted' => 1
		);
		if ($this->deal_model->save($data) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	/**
	 * 工程支付证书
	 **/
	public function payment(){
		$result = $this->deal_model
				->where(array(
					'id'	=> I('get.id',0,'intval')
				))
				->field("list_pricing,deducts_prepayment,supervision_amount,supervision_amount_words")
				->find();
		$this->assign("result", $result);
			
		$this->display();
	}
	
	/**
	 * 承包人开具收款发票通知书
	 **/
	public function paynotice(){
		$result = $this->deal_model
				->where(array(
					'id'	=> I('get.id',0,'intval')
				))
				->field("construction_amount,construction_amount_words")
				->find();
		$this->assign("result", $result);
		$this->display();
	}
	
	/**
	 * 施工进度
	 **/
	public function stepview(){
		// 查询左侧施工进度流程
		$type = "'1#病房楼','2#病房楼','3#病房楼','门诊医技楼','后勤值班楼','行政科研楼','高压氧舱楼','后勤服务楼','发热门诊楼','垃圾房','地下室','基坑围护'";
		$result = $this->PSummary_model
			->field("order_id as id,item_name as item,list_total_amount as contract,approved_total_amount as finish,cumulative_completion_percent as percent")
			->where("payment_review_id =". I('get.id',0,'intval') . " AND item_name IN(".$type.")")
			->select();
		$this->assign("items", $result);
		
		// 统计1-12月施工情况
		// 当前年
		$year = date('Y');
		$statistics = array();
		$approved = "[";
		$total = "[";
		for($i = 1; $i <= 12; $i++){
			$len = cal_days_in_month(CAL_GREGORIAN, $i, $year);
			$start = date('Y-'.$i.'-01 0:0:0');
			$end = date('Y-'.$i.'-'.$len.' 23:59:59');
			// 查询条件
			$where = "p.add_time >= '".$start."' AND p.add_time <= '" .$end. "' AND item_name = '总报价[一+二]'";
			// 拼接SQL查询语句
			$query = $this->PSummary_model->alias("s")
						->field('last_approved_accumulated_amount as total,approved_total_amount as approved')
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON s.payment_review_id = p.id',
						))
						->where($where)
						->order("p.add_time DESC")
						->find();
			//echo $this->PSummary_model->getLastSql(). "<br />";
			$statistics['approved'][$i] = $query ? $query['approved'] : 0;
			$statistics['total'][$i] = $query ? $query['total'] : 0;
			
			$approved .= ($query ? $query['approved'] : 0).",";
			$total .= ($query ? $query['total'] : 0).",";
		}
		$this->assign("statistics", $statistics);
		$this->assign("approved", substr($approved, 0, strlen($approved) - 1) . ']');
		$this->assign("total", substr($total, 0, strlen($total) - 1) . ']');
		
		//exit();
		$this->display();
	}
	
	/**
	 * 固定资产统计表
	 **/
	public function assetview(){
		$year = date('Y');
		$month = date('m');
		$statistics = array();
		for($i = 1; $i <= $month; $i++){
			$statistics[$i]['year'] = $year;
			$statistics[$i]['month'] = $i;
			
			$len = cal_days_in_month(CAL_GREGORIAN, $i, $year);
			$start = date('Y-'.$i.'-01 0:0:0');
			$end = date('Y-'.$i.'-'.$len.' 23:59:59');
			// 查询条件
			$where = "p.add_time >= '".$start."' AND p.add_time <= '" .$end. "' AND item_name = '总报价[一+二]'";
			// 当前月总报价
			$query = $this->PSummary_model->alias("s")
						->field('approved_total_amount as approved')
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON s.payment_review_id = p.id',
						))
						->where($where)
						->order("p.add_time DESC")
						->find();
			$statistics[$i]['approved'] = $query['approved'] !== NULL ? $query['approved'] : 0;
			// 年度累计
			$where = "p.add_time >= '".$year."-1-1 0:0:0' AND p.add_time <= '" .$end. "' AND item_name = '总报价[一+二]'";
			$query = $this->PSummary_model->alias("s")
						->field('SUM(approved_total_amount) as yearapproved')
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON s.payment_review_id = p.id',
						))
						->where($where)
						->order("p.add_time DESC")
						->find();
			$statistics[$i]['yearapproved'] = $query['yearapproved'] !== NULL ? $query['yearapproved'] : 0;
			// 历年累计
			$where = "p.add_time <= '" .$end. "' AND item_name = '总报价[一+二]'";
			$query = $this->PSummary_model->alias("s")
						->field('SUM(approved_total_amount) as yearsapproved')
						->join(array(
							' LEFT JOIN '.C('DB_PREFIX').'payment_review p ON s.payment_review_id = p.id',
						))
						->where($where)
						->order("p.add_time DESC")
						->find();
			$statistics[$i]['yearsapproved'] = $query['yearsapproved'] !== NULL ? $query['yearsapproved'] : 0;
		}
		$this->assign("statistics", $statistics);
		
		$this->display();
	}

}
?>